动态加载Javascript以及如何检查脚本是否存在 [英] Loading Javascript Dynamically and how to check if the script exists

查看:411
本文介绍了动态加载Javascript以及如何检查脚本是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下技术动态加载Javascript:

I am using the following technique to load up Javascript dynamically:

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "file.js";
document.body.appendChild(script);

这是一种非常常见的方法。
这里也讨论过: http:/ /www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/

It's quite a common approach. It's also discussed here: http://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/

我知道如何获得通知文件已加载并执行

I know how to get notified once the file has been loaded and executed

我不知道的是,如果Javascript源文件的链接被破坏,我该如何得到通知。

What I don't know is that if the link to the Javascript source file is broken how can I be notified.

谢谢

推荐答案

不考虑在脚本元素上侦听事件可靠(来源)。想到的一个选项是使用 setTimeout()来轮询您希望在外部脚本中定义的变量。在 x 秒之后,您可以超时轮询并将脚本视为已损坏。

Listening for events on script elements is not considered reliable (Source). One option that comes to mind is to use setTimeout() to poll for a variable that you expect to be defined in your external script. After x seconds, you could timeout your poll and consider the script as broken.

外部脚本:file.js :

External Script: file.js:

var MyLibrary = { };

主要文件:

var poll;
var timeout = 100; // 10 seconds timeout
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'file.js';
document.body.appendChild(script);

poll = function () {
  setTimeout(function () {
    timeout--;
    if (typeof MyLibrary !== 'undefined') {
      // External file loaded
    }
    else if (timeout > 0) {
      poll();
    }
    else {
      // External library failed to load
    }
  }, 100);
};

poll();

这篇关于动态加载Javascript以及如何检查脚本是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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