Javascript onload event - how to tell if script is already loaded?

六眼飞鱼酱① 提交于 2019-12-01 18:09:54

Why not add an id to the script element? Check to see if the id exists before continuing....

function includeJs(jsFilePath) {

  if (document.getElementById(jsFilePath+"_script")) {
    return;
  }
  var js = document.createElement("script");

  js.type = "text/javascript";
  js.id = jsFilePath+"_script";
  js.src = jsFilePath;

  document.body.appendChild(js); 
}

Lazy Implementation: Create an array that you can use to push the source of all loaded scripts onto, and as they load, push them onto the list. Each time, check to see if the given src is in the array, and if it is, fire the callback immediately.

What you do with the case when its appended, but not loaded becomes the question. If you want the callback to fire, but you want it to fire after it loads, you could do an associative array with a src as the key, and the script element as the value. From there, make the onload or onreadystatechange fire twice by wrapping the original, like so:

var temponload = element.onreadystatechange || element.onload;
if (element.onreadystatechange === undefined)
    element.onload = function(e) { temponload(); temponload(); };
else
    element.onreadystatechange = function (e) { temponload(); temponload(); };

You have other code which may need to hook into this, but this should get you started hopefully.

You can't really tell when a script has loaded. You can put a global variable in the script you want to check and then test for its presence.

There is a new project called LABjs (Loading and Blocking Javascript) in order to load scripts dynamically and thus tell when they are actually loaded (http://blog.getify.com/2009/11/labjs-new-hotness-for-script-loading/ <- check it out)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!