JavaScript-jquery $.getScript() 遇到js文件中含有document.write() 如何解决?

服务器管理 服务器管理 主题:1035 回复:2217

JavaScript-jquery $.getScript() 遇到js文件中含有document.write() 如何解决?

甜柠檬 发布于 2017-06-20 字数 104 浏览 1198 回复 4

举个例子:

a.js:

document.write('xx');

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

支持 Markdown 语法,需要帮助?

评论(4

清晨说ぺ晚安 2017-10-21 4 楼

需要调用a.ja的时候打开一个新的html,然后再让a.js里write到这个空dom里,然后再取出来,只是提供这样一种想法,不知道能不能实现

清晨说ぺ晚安 2017-08-29 3 楼

这种做法本身就存在很多问题,强烈不推荐。如果为了程序结构性更强,模块直接解耦,可以考虑使用一些JavascriptMVC框架如Backbone.js等,和模块加载框架RequireJs等

偏爱自由 2017-07-24 2 楼

总结一下你的问题:
1、就是想在dom加载完再去加载你的第三方js
2、当加载第三方js时出现document.write()不阻塞渲染
解决办法
1、通过js判断dom是否加载完成,
参考:等待HTML DOM加载
2、document.write虽然是浏览器原生的方法,但是也可以自定义一个方法来覆盖掉原来的方法。在javascript广告代码加载之前,重写document.write,等加载并执行完再改回来
参考:小巧独立的Javascript库(2):DomReady.js

以下是我修改的例子可以参考一下(测试通过):
domready.js

 (function(){
var DomReady = window.DomReady = {};
// Everything that has to do with properly supporting our document ready event. Brought over from the most awesome jQuery.
var userAgent = navigator.userAgent.toLowerCase();
// Figure out what browser is being used
var browser = {
version: (userAgent.match( /.+(?:rv|it|ra|ie)//: / ) || [])[1],
safari: /webkit/.test(userAgent),
opera: /opera/.test(userAgent),
msie: (/msie/.test(userAgent)) && (!/opera/.test( userAgent )),
mozilla: (/mozilla/.test(userAgent)) && (!/(compatible|webkit)/.test(userAgent))
};
var readyBound = false;
var isReady = false;
var readyList = [];
// Handle when the DOM is ready
function domReady() {
// Make sure that the DOM is not already loaded
if(!isReady) {
// Remember that the DOM is ready
isReady = true;
if(readyList) {
for(var fn = 0; fn < readyList.length; fn++) {
readyList[fn].call(window, []);
}
readyList = [];
}
}
};

// From Simon Willison. A safe way to fire onload w/o screwing up everyone else.  
function addLoadEvent(func) {  
  var oldonload = window.onload;  
  if (typeof window.onload != 'function') {  
    window.onload = func;  
  } else {  
    window.onload = function() {  
      if (oldonload) {  
        oldonload();  
      }  
      func();  
    }  
  }  
};  
// does the heavy work of working through the browsers idiosyncracies (let's call them that) to hook onload.  
function bindReady() {  
    if(readyBound) {  
        return;  
    }  
    readyBound = true;  
    // Mozilla, Opera (see further below for it) and webkit nightlies currently support this event  
    if (document.addEventListener &amp;&amp; !browser.opera) {  
        // Use the handy event callback  
        document.addEventListener("DOMContentLoaded", domReady, false);  
    }  

    // If IE is used and is not in a frame  

    // Continually check to see if the document is ready  

    if (browser.msie &amp;&amp; window == top) (function(){  
        if (isReady) return;  
        try {  
            // If IE is used, use the trick by Diego Perini  
            // http://javascript.nwbox.com/IEContentLoaded/  
            document.documentElement.doScroll("left");  
        } catch(error) {  
            setTimeout(arguments.callee, 0);  
            return;  
        }  
        // and execute any waiting functions  
        domReady();  

    })();  

    if(browser.opera) {  
        document.addEventListener( "DOMContentLoaded", function () {  
            if (isReady) return;  
            for (var i = 0; i &lt; document.styleSheets.length; i++)  
                if (document.styleSheets[i].disabled) {  
                    setTimeout( arguments.callee, 0 );  
                    return;  
                }  
            // and execute any waiting functions  
            domReady();  
        }, false);  

    }  
    if(browser.safari) {  
        var numStyles;  
        (function(){  
            if (isReady) return;  
            if (document.readyState != "loaded" &amp;&amp; document.readyState != "complete") {  
                setTimeout( arguments.callee, 0 );  
                return;  
            }  
            if (numStyles === undefined) { 
                var links = document.getElementsByTagName("link");  
                for (var i=0; i &lt; links.length; i++) {  
                    if(links[i].getAttribute('rel') == 'stylesheet') {  
                        numStyles++;  
                    }  
                }  
                var styles = document.getElementsByTagName("style");  
                numStyles += styles.length;  
            }  
            if (document.styleSheets.length != numStyles) {  
                setTimeout( arguments.callee, 0 );  
                return;  
            }  
            // and execute any waiting functions  
            domReady();  
        })();  

    }  
    // A fallback to window.onload, that will always work  
    addLoadEvent(domReady);  
};  

// This is the public function that people can use to hook up ready.  
DomReady.ready = function(fn, args) {  
   // Attach the listeners  
    bindReady();  
    // If the DOM is already ready  
    if (isReady) {  
        // Execute the function immediately  
        fn.call(window, []);  
    } else {  
        // Add the function to the wait list  
       readyList.push( function() { return fn.call(window, []); } );  
   }  

};  
bindReady();  

})();

testDomReady.html

 <html>
<head>
<title>Testing DOM Loading</title>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript" src="domready.js"></script>
<script type="text/javascript">
/**

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

  • @param { Dom Object } textarea元素
    */
    var loadScript = function( jsurl,toobj ){
    var url = jsurl,
    // 缓存原生的document.write
    docWrite = document.write,
    // 创建一个新script来加载
    script = document.createElement( 'script' ),
    head = document.head ||
    document.getElementsByTagName( 'head' )[0] ||
    document.documentElement;

    // 重写document.write
    document.write = function( text ){
    document.getElementById(toobj).innerHTML = text;
    };
    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 =""
         script =""
         script.onerror =""
         script.onload =""
         script.onreadystatechange = null;
     }

    }

    // 加载script
    head.insertBefore( script, head.firstChild );
    };

 function tag(name, elem) {
     //如果上下文元素未提供,则搜索整个文档
     return (elem || document).getElementsByTagName(name);
 }

 DomReady.ready(function(){
    alert('dom is ready');   
    tag("h1")[0].style.border = "4px solid black";
    var obj=document.getElementById('tjs');
    loadScript('a.js',"tjs");
});   

</script>

</head>
<body>
<h1 id='tjs'>test</h1>
</body>
</html>

偏爱自由 2017-07-02 1 楼

有没有想过重写 document.write ?

 <div id="test">
</div>
<script>
var script_string = "";
$(function(){
document.write = function(evil) {
script_string += evil;
}
$.getScript('a.js').done(function(){
$('#test').append(script_string);
});
})
</script>