首页 > 学院 > 开发设计 > 正文

重写document.write实现无阻塞加载script

2019-11-06 08:20:32
字体:
来源:转载
供稿:网友
document.write是在页面渲染的时候同步进行的,必须要等javascript代码下载好并且document.write执行完后才接着渲染后面的内容,如果东西比较多的话,就会导致页面阻塞,会让用户觉得你这个网页很慢,解决办法如下:

重写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'));
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表