如何查找链接的异步脚本是否已加载? [英] How to find if the chained asynchronous scripts has been loaded?

查看:95
本文介绍了如何查找链接的异步脚本是否已加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是场景.我正在执行$.getScript()函数调用以在我的javascript文件中获取脚本.我从$.getScript()下载的脚本尝试下载它依赖的其他一些脚本.在我的脚本中,我正在使用done()来检查脚本是否完全加载.如果确实如此,那么我尝试调用不在刚刚从$.getScript表单加载的脚本上的函数,而是在其中加载的脚本的函数.

Here's the scenario. I am doing a $.getScript()function call to get a script in my javascript file. The script that I'm downloading from the $.getScript() tries to download some other scripts that it's dependent on. In my script I'm using done() to check if the script loaded completely or not. And if it did, then I try calling the function that's not on the script that I just loaded form $.getScript but the script that was loaded in it.

令人困惑,所以让我用一些代码演示:-

It's getting confusing so let me demonstrate with some code:-

//my script.js
$.getScript("http://myexternaljs.com/first.js").done(function(){
    doSecond(); //<- this resides in second.js which is being called in first.js below
}

//first.js
(function(){
    $.getScript("http://firstexternal.com/second.js");
}());

//second.js
function doSecond(){
    return console.log("hello world");
}

这里的问题是second.js需要花费一些时间下载,因此我在done()上调用doSecond()时不断出现doSecond() is undefined错误.

The problem here is second.js takes a little time to download so I keep getting doSecond() is undefined error on my call to doSecond() on done().

我可以使用超时并检查是否加载了second.js,但是有更好的方法吗?

I could use a timeout and check if second.js loaded or not but is there a better way to do this?

我也愿意接受任何AMD loadersPromises答案.

I'm open to any AMD loaders or Promises answers as well.

推荐答案

您还可以使用 $.ajaxSuccess :

You can also use $.ajaxSuccess:

$(document).ajaxComplete(function(ev, jqXhr, options) {
  // You could be as specific as you need to here.
  if ( options.url.match('second.js') ) {
    doSecond();
  }
});

或者,您可以在ajaxComplete内执行此操作:

Alternatively, you could do this inside ajaxComplete:

$(document).ajaxComplete(function(ev, jqXhr, options) {
  // You could simplify to 
  // doSecond && doSecond()
  // if you can trust that it will always be a function
  if ( doSecond && $.isFunction(doSecond) ) {
    doSecond();
  }
});

这篇关于如何查找链接的异步脚本是否已加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆