等待脚本加载

时间:2014-05-26 18:56:58

标签: javascript jquery

在浏览器的控制台中尝试以下代码:

var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://code.jquery.com/jquery-2.1.1.min.js';
script.async = true;
document.body.appendChild(script);

console.log($);

然后等几秒再做一遍:

console.log($);

因此加载jQuery需要一段时间。我尝试了this suggestion,这似乎是所有相关问题的共识:

+function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}("http://code.jquery.com/jquery-1.7.1.min.js", function(){console.log($);});

再次它不起作用...... enter image description here 第一个console.log($)应该给出正确的结果。 如果jQuery加载并执行 ,我该怎么办才能执行函数?

(背景:我正在编写Chrome扩展程序以修复不使用jQuery的页面上的格式。)

1 个答案:

答案 0 :(得分:1)

function loadScript(url, callback){
    var foo1 = document.createElement('script');
    foo1.type = 'text/javascript';
    foo1.setAttribute('src', url);

    foo1.onreadystatechange = callback;
    foo1.onload = callback;

    var head = document.getElementsByTagName('head')[0];
    head.appendChild(foo1, head);
}
loadScript(('https:' == document.location.protocol ? 'https://' : 'http://') +'code.jquery.com/jquery-1.11.0.min.js', function(){
    console.log($);
});