动态包含jquery文件

时间:2014-02-18 12:52:58

标签: javascript jquery

我希望在需要时动态包含jquery文件 但是有一个问题,出现的错误消息 $ is not defined

我做了什么:

// include the file dynamically.
var parent, script;
parent = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.type = "text/javascript";
script.src = "includes/jquery.js";
parent.appendChild(script);

// The usage
$('#box').remove();

3 个答案:

答案 0 :(得分:1)

处理onload事件以确保在使用之前加载脚本

script.onload = function () { $('#box').remove() }
parent.appendChild(script);

答案 1 :(得分:1)

对于IE,我认为您需要使用onreadystatechange回调。 E.g。

script.onload = script.onreadystatechange = function() {
if (!script.readyState || script.readyState == 'loaded' ||
    script.readyState == 'complete') {
  $('#box').remove();
}
};

答案 2 :(得分:0)

试试这个:

(function () {

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);
}

loadScript("includes/jquery.js", function () {

     //jQuery loaded
     console.log('jquery loaded');
     $('#box').remove();

});


})();