重写document.write实现无阻塞加载script
/* 全局存储变量 */
var global = { variable : {},//数据变量 cache : {},//数据缓存 sitepath : '/',//网站根目录 loadScript : {},//延迟加载 loadScriptId : [],//延迟加载Id loadScriptNum : 0,//当前加载元素 loadScriptT : '',//延迟开关}/* 全局方法 */
var common = { /** * 重写document.write实现无阻塞加载script * @param { Dom Object } textarea元素 */ loadScript : function( elem ){ if(elem != undefined){ if(global.loadScriptT != 0 && global.loadScriptT != undefined){ clearTimeout(global.loadScriptT); } global.loadScript[elem.id] = elem; global.loadScriptT = setTimeout(function(){ for(var a in global.loadScript){ global.loadScriptId.push(a); } common.loadScriptOrder(global.loadScriptNum); },300); } }, loadScriptAuto : function(){ $('textarea[id^=loadScript]').each(function(a,b){ common.loadScript(b); }); }, loadScriptOrder : function(i){ clearTimeout(global.loadScriptT); if(global.loadScriptId[i] != undefined){ global.loadScriptT = setTimeout(function(){ common.loadScriptRun(global.loadScript[global.loadScriptId[i]]); global.loadScriptNum = i+1; common.loadScriptOrder(global.loadScriptNum); },300); } }, loadScriptRun : function( elem ){ if(typeof elem == 'undefined') return; var url = elem.value.match( /src="([/s/S]*?)"/i )[1]; // 缓存原生的document.write var docWrite = document.write; // 创建一个新script来加载 var script = document.createElement( 'script' ); var head = document.head || document.getElementsByTagName( 'head' )[0] || document.documentElement; // 重写document.write document.write = function( text ){ $('#'+elem.id).replaceWith($(text)); //elem.parentNode.replaceChild(text,elem); }; script.type = 'text/Javascript'; script.src = url; script.onerror = script.onload = script.onreadystatechange = function( e ){ e = e || window.event; if( !script.readyState || /loaded|complete/.test(script.readyState) ||e === 'error'){ // 恢复原生的document.write document.write = docWrite; head.removeChild( script ); // 卸载事件和断开DOM的引用 // 尽量避免内存泄漏 head = elem = script = script.onerror = script.onload = script.onreadystatechange = null; } } // 加载script head.insertBefore( script, head.firstChild ); delete global.loadScript[elem.id]; },}使用方法
引入js文件,然后调用方法
common.loadScript(document.getElementById('idname'));新闻热点
疑难解答