用于检测何时加载外部 javascript 的 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8718303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:20:33  来源:igfitidea点击:

JavaScript to detect when external javascripts are loading

javascript

提问by Dan

Is there a way (event listener or otherwise) to detect when a particular external javascript is about to load / is loading / has finished loading?

有没有办法(事件侦听器或其他方式)检测特定外部 javascript 何时即将加载/正在加载/已完成加载?

In otherwords, does the browser fire an event when it's about to load, is loading, and/or has finished loading a particular external script?

换句话说,浏览器是否会在即将加载、正在加载和/或已完成加载特定外部脚本时触发事件?

For my purposes it's not enough to simply check to see if a known object exists or anything like that. Instead, I need something that will detect a JS file is loading/loaded regardless of the contents of the JS file.

就我而言,仅仅检查是否存在已知对象或类似的东西是不够的。相反,我需要一些可以检测 JS 文件正在加载/加载的东西,而不管 JS 文件的内容如何。

回答by Francis

The following example works in Chrome. It attaches an handler on the onload event of the head tag and then adds an external javascript file. When the file is loaded, the event is captured and an alert appears.

以下示例适用于 Chrome。它在 head 标签的 onload 事件上附加一个处理程序,然后添加一个外部 javascript 文件。加载文件后,将捕获事件并显示警报。

http://jsfiddle.net/francisfortier/uv9Fh/

http://jsfiddle.net/francisfortier/uv9Fh/

window.onload = function() {
    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement("script"); 

    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "http://code.jquery.com/jquery-1.7.1.min.js");

    head.addEventListener("load", function(event) {
        if (event.target.nodeName === "SCRIPT")
        {
            alert("Script loaded: " + event.target.getAttribute("src"));
        }
    }, true);

    head.appendChild(script); 
}

回答by u.k

Since all browsers blocks the "UI thread" when processing <script>tags, you can rely that pre-existing tags are loaded.

由于所有浏览器在处理<script>标签时都会阻塞“UI 线程” ,因此您可以依赖加载预先存在的标签。

If you are loading a script dynamically, you can listen to the load event of the <script>tag.

如果是动态加载脚本,可以监听<script>标签的加载事件。

function loadScript(src, callback) {
    var script  = document.createElement("script");
    script.setAttribute("src", src);
    script.addEventListener("load", callback);
    document.getElementsByTagName("script")[0].insertBefore(script);
};

loadScript("http://code.jquery.com/jquery-1.7.1.min.js", function(){
    alert("loading is done");
});

回答by pmrotule

I wrote a script for those who wants to call a function after all external files (dynamically added) are loaded. It goes like this:

我为那些想要在加载所有外部文件(动态添加)后调用函数的人编写了一个脚本。它是这样的:

var file = [];
var loaded = [];
var head = document.getElementsByTagName('head')[0];

var fileOnLoad =
// Pass the arrays to your function
(function(file, loaded){ return function(){
  
  loaded.push(true);
  
  // Print the number of files loaded
  document.getElementById("demo").innerHTML +=
   "<br>"+loaded.length+" files loaded";
  
  if(file.length == loaded.length){
    
    alert("All files are loaded!");
  }
}})(file, loaded);

////////////////////////////////////////////////
////                                        ////
////   Add the external files dynamically   ////
////                                        ////
////////////////////////////////////////////////

file[0] = document.createElement('script');
file[0].src =
"https://maps.googleapis.com/maps/api/js?v=3.exp";
file[0].onload = fileOnLoad;
head.appendChild(file[0]);

file[1] = document.createElement('script');
file[1].src =
"http://code.jquery.com/jquery-latest.js";
file[1].onload = fileOnLoad;
head.appendChild(file[1]);

file[2] = document.createElement('script');
file[2].src =
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js";
file[2].onload = fileOnLoad;
head.appendChild(file[2]);

file[3] = document.createElement('link');
file[3].rel = "stylesheet";
file[3].href =
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css";
file[3].onload = fileOnLoad;
head.appendChild(file[3]);

file[4] = document.createElement('link');
file[4].rel = "stylesheet";
file[4].href =
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css";
file[4].onload = fileOnLoad;
head.appendChild(file[4]);
<div id="demo">0 file loaded</div>

Hope it helps!

希望能帮助到你!

回答by Júlio Santos

If you can use jQuery, try $.getScript(). Docs here.

如果您可以使用 jQuery,请尝试$.getScript(). 文档在这里

回答by tkone

<script onload>will fire when a script is finished loading.

<script onload>脚本加载完成后将触发。

You will notbe able to do something like:

将无法执行以下操作:

<script src="/foo.js"></script>
<script src="/bar.js"></script>
<script>
function alertonload(src){
   console.log(src+' is loaded');
}
scripts = document.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
    scripts[i].onload = function(){ alertonload(scripts[i].src); };
}
</script>

This is pure conjecture and speculation; I have not tried it and there's probably better ways to write it, but this will notdo what you're looking to do. EDIT: The scripts are loaded as the browser sees them, not after the fact. They will be loaded before this occurs.

这纯属猜想和推测;我还没有尝试过,可能有更好的方法来编写它,但这不会做你想做的事情。编辑:脚本在浏览器看到它们时加载,而不是事后加载。它们将在这发生之前加载。