document.head.appendChild无法正常工作

时间:2015-04-05 19:49:26

标签: javascript jquery html

我试图通过JavaScript代码附加jQuery库,如下所示:

    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'
    document.head.appendChild(script);

if (window.jQuery) {  
    document.write('jQuery is loaded') 
} else {
    document.write('jQuery is not loaded');
}

上面的代码没有执行src文件,我无法找到jQuery元素。为了确认我已经添加了这段代码:

if (window.jQuery) {  
    document.write('jQuery is loaded') 
} else {
    document.write('jQuery is not loaded');
}

JsFiddle:https://jsfiddle.net/vyeyhrrL/

我看到的输出是“jQuery未加载”。

你能让我知道我错过了什么吗?

编辑:

感谢评论,这是有效的:

    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
script.onload = function(script){
            console.log(script + ' loaded!');
if (window.jQuery) {  
    document.write('jQuery is loaded') 
} else {
    document.write('jQuery is not loaded');
}
        };
    document.head.appendChild(script);

0 个答案:

没有答案