【问题标题】:Wait for script to load [duplicate]等待脚本加载[重复]
【发布时间】:2014-05-26 18:56:57
【问题描述】:

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

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

再一次它不起作用...... 第一个console.log($) 应该给出正确的结果。 jQuery 加载并执行后,我可以做些什么来执行函数

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

【问题讨论】:

标签: javascript jquery


【解决方案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($);
});

【讨论】:

    猜你喜欢
    • 2012-07-23
    • 1970-01-01
    • 2011-07-21
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多