动态加载 Javascript 以及如何检查脚本是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3768768/
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-08-23 06:04:13  来源:igfitidea点击:

Loading Javascript Dynamically and how to check if the script exists

javascript

提问by Lx1

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

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

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

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

这是一种很常见的方法。这里也讨论过: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

我知道如何在文件加载和执行后得到通知

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

我不知道的是,如果指向 Javascript 源文件的链接已损坏,我将如何收到通知。

Thanks

谢谢

回答by Daniel Vassallo

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 xseconds, you could timeout your poll and consider the script as broken.

侦听脚本元素上的事件被认为是不可靠的(Source)。想到的一种选择是使用setTimeout()轮询您希望在外部脚本中定义的变量。之后x秒钟,你可以超时的调查,并考虑脚本打破。

External Script: file.js:

外部脚本:file.js:

var MyLibrary = { };

Main document:

主要文件:

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

回答by Dinh Tran

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

You need to add a callback for this script.

您需要为此脚本添加回调。

1st:Create the call back:

第一:创建回调:

function callbackFn(callbackArgs) = {
       console.log("script is loaded with the arguments below");
       console.log(callbackArgs);
    }

2nd:Add an event listener to the script. Both Firefox and Chrome support onload event so you can use it like this:

第二:向脚本添加事件侦听器。Firefox 和 Chrome 都支持 onload 事件,因此您可以像这样使用它:

script.onload = callbackFn();

For IE... You can add an event listener for a state change like this:

对于 IE... 您可以为状态更改添加一个事件侦听器,如下所示:

script.onreadystatechange = function() {
    if ( this.readyState != "loaded" ) return;
    callbackFn();
    }

Last:Append the script to the body like you used to do.

最后:像以前一样将脚本附加到正文中。

document.body.appendChild(script);

For further information, please refer to this acticle.

有关更多信息,请参阅此操作

回答by Randy the Dev

It's pretty easy, Internet Explorer will trigger an onreadystatechangeevent while others will trigger a onloadevent for the script object.

这很简单,Internet Explorer 将触发一个onreadystatechange事件,而其他人将触发onload脚本对象的事件。

var newScript;
var loadFunc = function ()
{
    alert("External Javascript File has been loaded");
};
newScript = document.createElement('script');
newScript.setAttribute('type','text/javascript');
newScript.setAttribute('src','file.js');

//IE triggers this event when the file is loaded
if (elm.attachEvent)
{
    newScript.attachEvent('onreadystatechange',function() 
    {
        if (newScript.readyState == 'complete' || newScript.readyState == 'loaded')
            loadFunc();
    });
}

//Other browsers trigger this one
if (newScript.addEventListener)
    newScript.addEventListener('load', loadFunc, false);

document.getElementsByTagName('head')[0].appendChild(newScript);

回答by Apostolos

Loading a script dynamically is much more simple:

动态加载脚本要简单得多:

var script = document.createElement('script');
script.onload = function () {
  main_function();  // Main function to call or anything else or nothing  
};
script.src = "yourscript.js";
document.head.appendChild(script);    

回答by Sumit Raju

You can append an onloadattribute and in that attribute, you can call a function which will be executed after the JS file has loaded.

您可以附加一个onload属性,并在该属性中调用一个函数,该函数将在 JS 文件加载后执行。

Check the code:

检查代码:

var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
jsElement.src = "http://code.jquery.com/jquery-latest.min.js";
jsElement.setAttribute("onload","getMeAll()");
document.body.appendChild(jsElement);
function getMeAll(){
    //your code goes here
}

Hope this helps.

希望这可以帮助。

回答by Syed

Recently in my vue.js project I tried to something like this, I am using es6 so make sure you have the setup. This is just vanilla javascript, so this should run without any issue.

最近在我的 vue.js 项目中,我尝试了这样的操作,我使用的是 es6,所以请确保你有设置。这只是普通的 javascript,所以它应该运行没有任何问题。

function handleLoad() {
  // on scirpt loaded logic goes here
  ...
};

function handleLoadError(yourScript) {
  // on scirpt loading error logic goes here
  ...

  // remove the script element from DOM if it has some error
  document.head.removeChild(yourScript);
};

function generatePan(token) {
  // if script does not exist only then append script to DOM
  if (!document.getElementById('your-script')) {
    const yourScript = document.createElement('script');
    yourScript.setAttribute('src', 'https://your-script.js');
    yourScript.setAttribute('id', 'your-script');
    yourScript.async = true;
    yourScript.addEventListener('load', () => handleLoad(), false);
    yourScript.addEventListener('error', () => handleLoadError(yourScript), false);

    document.head.appendChild(yourScript);
  } else {
    // runs if script is already loaded DOM
    handleLoad();
  }
};

Also, please check this link, even this may help.

另外,请检查此链接,即使这可能会有所帮助。

回答by JochenJung

One way would be to define a variable in the script you include and then check whether this variable is defined, or not.

一种方法是在您包含的脚本中定义一个变量,然后检查该变量是否已定义。

回答by Gus Crawford

In the onload event, there are status codes. 200 is good, 404 as you may recall means a file is not found. Helpful?

在 onload 事件中,有状态码。200 是好的,您可能还记得 404 表示找不到文件。有用吗?

回答by ?ime Vidas

What JavaScript library do you use?

你使用什么 JavaScript 库?

In jQuery if you load the script via Ajax, you have an option to run a success callback function (and other types of callbacks)...

在 jQuery 中,如果您通过 Ajax 加载脚本,则可以选择运行成功回调函数(和其他类型的回调)...

There is also a dedicated function for loading scripts: $.getScript()

还有一个专门的脚本加载函数:$.getScript()