How to load third-party javascript tag asynchronously which has [removed]

前端 未结 7 1044
星月不相逢
星月不相逢 2021-01-04 07:16

We give out a piece of javascript tags such as which site owners put on their site like http://exa

相关标签:
7条回答
  • 2021-01-04 07:47

    You can support script injection the correct way by intercepting calls to document.write in this way:

    document.writeText = document.write;
    
    document.write = function(parameter) {
        if (!parameter) return; 
        var scriptPattern = /<script.*?src=['|"](.*?)['|"]/;
        if (scriptPattern.test(parameter)) {
            var srcAttribute = scriptPattern.exec(parameter)[1];
            var script = document.createElement('script');
            script.src = srcAttribute;
            document.head.appendChild(script); 
        }
        else {
            document.writeText(parameter);
        }   
    };
    

    Obviously this can be condensed down a bit further, but the variable names are included for clarity.

    Source

    0 讨论(0)
提交回复
热议问题