简体   繁体   English

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

[英]Loading Javascript Dynamically and how to check if the script exists

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谢谢

Listening for events on script elements is not considered reliable ( Source ).侦听脚本元素上的事件被认为是不可靠的( 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.想到的一种选择是使用setTimeout()来轮询您希望在外部脚本中定义的变量。 After x seconds, you could timeout your poll and consider the script as broken. 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();
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 .有关更多信息,请参阅此操作

It's pretty easy, Internet Explorer will trigger an onreadystatechange event while others will trigger a onload event 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);

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

You can append an onload attribute 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.希望这会有所帮助。

In the onload event, there are status codes.在 onload 事件中,有状态码。 200 is good, 404 as you may recall means a file is not found. 200 是好的,您可能还记得 404 表示找不到文件。 Helpful?有用吗?

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

Recently in my vue.js project I tried to something like this, I am using es6 so make sure you have the setup.最近在我的 vue.js 项目中,我尝试了这样的操作,我使用的是 es6,所以请确保你有设置。 This is just vanilla javascript, so this should run without any issue.这只是普通的 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.另外,请检查此链接,即使这可能会有所帮助。

Sorry for the necroposting, but this was my first hit for this exact situation and I believe I have found a better answer: (at least) now you can do the onload event callback from any HTML element to execute code after loaded into the DOM, and you can use it like this:抱歉发布了 necroposting,但这是我针对这种确切情况的第一次点击,我相信我找到了一个更好的答案:(至少)现在你可以从任何 HTML 元素执行onload事件回调以在加载到 DOM 后执行代码,你可以这样使用它:

const script = document.createElement("script");
script.type = "text/javascript";
script.src = "file.js";
script.onload(() => {
    // ...whatever you want to excecute after loadinng the script
})
document.body.appendChild(script);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM