jquery js 动态加载 js文件

张映 发表于 2015-02-11

分类目录: nodejs/vue/js/jquery

标签:, ,

如果用jquery append直接加载script标签的话,会报错的。除了document.write外,还有没有其他的比较好的动态加载js文件的方法。

1,jquery方法

$.getScript("./test.js");   //加载js文件

$.getScript("./test.js",function(){   //加载test.js,成功后,并执行回调函数
    console.log("加载js文件");
});

2,js方法

<html>
<body>
</body>
</html>
<script type="text/javascript">
function loadScript(url, callback) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    if(typeof(callback) != "undefined"){
        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else {
            script.onload = function () {
                callback();
            };
        }
    }
    script.src = url;
    document.body.appendChild(script);
}

loadScript("http://code.jquery.com/jquery-latest.js", function () {  //加载,并执行回调函数
    alert($(window).height());
});

//loadScript("http://code.jquery.com/jquery-latest.js");  //加载js文件
</script>


转载请注明
作者:海底苍鹰
地址:http://blog.51yip.com/jsjquery/1705.html?f=http%3A%2F%2Fblogread.cn%2F