动态加载javascript src

时间:2014-04-17 10:06:57

标签: javascript jquery

我有一个javascript代码如下:

<script type="text/javascript"
src="https://secure.echosign.com/public/widget?f=8KX2X55PXF274A"
></script>

我从上面的javascript中获取src属性值,并在使用javascript加载页面后将其添加到div标记中:

var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", src);
var div = document.getElementById("dialog");
div.appendChild(script);

脚本在运行时添加到div中:

<script type="text/javascript"
src="https://secure.echosign.com/public/widget?f=8JWIPSI2G2T2FG"></script>

但是这个javascript代码没有在运行时执行/加载。其src指向第三方内容。

1 个答案:

答案 0 :(得分:0)

我昨天也回答了这样的话。我想你正在寻找这样的东西。

window.onload = function() {
   alert('Page Loaded. Loading script now ....');
   var url = 'https://secure.echosign.com/public/widget?f=8KX2X55PXF274A';
   loadScript(url, callback)
}

var callback = function() {
    alert('Script Loaded !');
}

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

JsFiddle:https://jsfiddle.net/nikdtu/Lgg1sqnk/

如果要动态加载多个脚本,请阅读此链接Dynamically load several JS files and fire a callback when all are ready