Javascript onload 事件 - 如何判断脚本是否已经加载?

发布于 2024-10-10 10:31:36 字数 2781 浏览 4 评论 0原文

如何使用 javascript 确定 HTMLScriptElement 是否已完全加载?

如何确定动态加载的脚本是否已完成加载而无需使用 onload 或 onreadystate 更改事件?

代码如下:

   TOOL.loadScript = function (url, callback, reappend, deepSearch) {
      var head, curr, child, tempScript, alreadyAppended, queue, 
      alreadyHandled, script, handler, loadFunc; 

      head = document.getElementsByTagName("head")[0];
      tempScript = document.createElement("script");
      tempScript.src = url;
      alreadyAppended = false;

      queue = []; 

      if (deepSearch) {
         // search entire document
         queue.push(document.firstElementChild);
      }
      else { 
         // just search the head element
         queue.push(head); 
      }

      while (queue.length !== 0) { 
         curr = queue.shift();

         // add child nodes to queue
         child = curr.firstElementChild; 
         if (child !== null && child !== undefined) { 
            queue.push(child);
            child = child.nextElementSibling;
            while (child !== null && child !== undefined) { 
               queue.push(child);
               child = child.nextElementSibling;
            } 
         }

         if (curr.tagName !== null && curr.tagName !== undefined) {
            if (curr.tagName.toLowerCase() === "script" && curr.src === tempScript.src) {
               script = curr;
               alreadyAppended = true;
               break;
            }
         }
      }

      if (!alreadyAppended) { 
         script = document.createElement("script");
         script.type = "text/javascript"; 
         script.async = true; 
         script.src = url; 
      } 

      alreadyHandled = false; 

      handler = function (event) {
         console.log("handling event..."); 
         if (!alreadyHandled) { 
            if ((!event.readyState) || (event && (event.readyState === "loaded" || event.readyState === "complete"))) {  
               alreadyHandled = true; 
               callback.apply(script, [url]);
               if (loadFunc) { 
                  loadFunc.apply(script, arguments); 
               }
            }
         }
      }; 

      if (script.onreadystatechange === undefined) { 
         loadFunc = script.onload;
         script.onload = handler; 
      } 
      else { 
         loadFunc = script.onreadystatechange; 
         script.onreadystatechange = handler; 
      } 

我这里需要帮助。我希望即使 alreadyAppeneded === true 并且相同的脚本已加载,回调函数也会触发,但前提是该脚本完全完成加载。

      if (!alreadyAppended || (alreadyAppended && reappend)) { 
         head.appendChild(script); 
      } 
   };

底线:如何确定脚本是否已完成加载?如果需要请向我提问。

谢谢。

How can I use javascript to determine if an HTMLScriptElement has already been fully loaded?

How can I determine if a dynamically loaded script has finished loading without using the onload or onreadystate change events?

Code is as follows:

   TOOL.loadScript = function (url, callback, reappend, deepSearch) {
      var head, curr, child, tempScript, alreadyAppended, queue, 
      alreadyHandled, script, handler, loadFunc; 

      head = document.getElementsByTagName("head")[0];
      tempScript = document.createElement("script");
      tempScript.src = url;
      alreadyAppended = false;

      queue = []; 

      if (deepSearch) {
         // search entire document
         queue.push(document.firstElementChild);
      }
      else { 
         // just search the head element
         queue.push(head); 
      }

      while (queue.length !== 0) { 
         curr = queue.shift();

         // add child nodes to queue
         child = curr.firstElementChild; 
         if (child !== null && child !== undefined) { 
            queue.push(child);
            child = child.nextElementSibling;
            while (child !== null && child !== undefined) { 
               queue.push(child);
               child = child.nextElementSibling;
            } 
         }

         if (curr.tagName !== null && curr.tagName !== undefined) {
            if (curr.tagName.toLowerCase() === "script" && curr.src === tempScript.src) {
               script = curr;
               alreadyAppended = true;
               break;
            }
         }
      }

      if (!alreadyAppended) { 
         script = document.createElement("script");
         script.type = "text/javascript"; 
         script.async = true; 
         script.src = url; 
      } 

      alreadyHandled = false; 

      handler = function (event) {
         console.log("handling event..."); 
         if (!alreadyHandled) { 
            if ((!event.readyState) || (event && (event.readyState === "loaded" || event.readyState === "complete"))) {  
               alreadyHandled = true; 
               callback.apply(script, [url]);
               if (loadFunc) { 
                  loadFunc.apply(script, arguments); 
               }
            }
         }
      }; 

      if (script.onreadystatechange === undefined) { 
         loadFunc = script.onload;
         script.onload = handler; 
      } 
      else { 
         loadFunc = script.onreadystatechange; 
         script.onreadystatechange = handler; 
      } 

I need help here. I want the callback function to fire even if alreadyAppeneded === true and the same script was already loaded, but only if that script is completely finished loading.

      if (!alreadyAppended || (alreadyAppended && reappend)) { 
         head.appendChild(script); 
      } 
   };

BOTTOM LINE: How do I determine if a script has completed loading? Please ask me questions if needed.

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

剑心龙吟 2024-10-17 10:31:36

为什么不给 script 元素添加一个 id 呢?在继续之前检查该 id 是否存在......

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

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); 
}
绾颜 2024-10-17 10:31:36

惰性实现:创建一个数组,您可以使用该数组将所有加载的脚本的源推送到上面,并在加载脚本时将它们推送到列表中。每次,检查给定的 src 是否在数组中,如果在,则立即触发回调。

当案例被附加但未加​​载时,您如何处理它成为问题。如果您希望回调触发,但希望它在加载后触发,您可以创建一个关联数组,其中 src 作为键,脚本元素作为值。从那里,通过包装原始代码使 onload 或 onreadystatechange 触发两次,如下所示:

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

您还有其他代码可能需要挂钩到此,但这应该可以帮助您开始。

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.

凌乱心跳 2024-10-17 10:31:36

您无法真正判断脚本何时加载。您可以将全局变量放入要检查的脚本中,然后测试它是否存在。

有一个名为 LABjs(加载和阻止 Javascript)的新项目,用于动态加载脚本,从而判断它们何时实际加载(http://blog.getify.com/2009/11/labjs-new-hotness-for-脚本加载/<-检查一下)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文