动态脚本加载同步 [英] dynamic script loading synchronization

查看:164
本文介绍了动态脚本加载同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本知道加载包含javascript类的动态脚本。
我正在使用以下代码加载类脚本:

I have a script that knows to load dynamiclly scripts that contains javascript classes. i'm loading the class script using the following code:

var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "myscript.js";
head.appendChild(script);

然后我尝试使用eval创建新类:

i'm then trying to create the new class using eval:

var classObj = eval(" new MyClass()" );

问题是eval的代码正在执行bofre脚本已加载到内存中我得到一个错误, MyClass未定义。

the problem is that the code of the eval is being executed bofre the script has been loaded into memory and i get an error that the MyClass is undefined.

有没有办法同步这些事件?我需要确保脚本完全加载到内存中才能开始从中分配类。

Is there a way to synch these events? i need to make sure the script is fully being loaded into memory before i can start allocating classes from it.

推荐答案

你需要将事件处理程序附加到onload方法,符合Web标准的浏览器或onreadystatechange,在Internet Explorer中检查script.readyState属性是否等于loaded或complete。

You need to attach an event handler to either the onload method, in browsers compliant with Web standards, or the onreadystatechange, checking for the script.readyState property getting equal to "loaded" or "complete", in Internet Explorer.

在收到脚本加载通知之前,您可能正在尝试访问尚未声明或创建的对象,函数和属性。

Before you get notified that the script was loaded, you are probably trying to access objects, functions and properties that have not been declared or created yet.

以下是一个示例函数,摘自模块 bezen.dom.js 在我的 Javascript库,bezen.org 中:

Here is an example function, extracted from the module bezen.dom.js in my Javascript library, bezen.org:

var appendScript = function(parent, scriptElt, listener) {
    // append a script element as last child in parent and configure 
    // provided listener function for the script load event
    //
    // params:
    //   parent - (DOM element) (!nil) the parent node to append the script to
    //   scriptElt - (DOM element) (!nil) a new script element 
    //   listener - (function) (!nil) listener function for script load event
    //
    // Notes:
    //   - in IE, the load event is simulated by setting an intermediate 
    //     listener to onreadystate which filters events and fires the
    //     callback just once when the state is "loaded" or "complete"
    //
    //   - Opera supports both readyState and onload, but does not behave in
    //     the exact same way as IE for readyState, e.g. "loaded" may be
    //     reached before the script runs.

    var safelistener = catchError(listener,'script.onload');

    // Opera has readyState too, but does not behave in a consistent way
    if (scriptElt.readyState && scriptElt.onload!==null) {
      // IE only (onload===undefined) not Opera (onload===null)
      scriptElt.onreadystatechange = function() {
        if ( scriptElt.readyState === "loaded" || 
             scriptElt.readyState === "complete" ) {
          // Avoid memory leaks (and duplicate call to callback) in IE
          scriptElt.onreadystatechange = null;
          safelistener();
        }
      };
    } else {
      // other browsers (DOM Level 0)
      scriptElt.onload = safelistener;
    }
    parent.appendChild( scriptElt );
};

为了使其适应您的需要,您可以替换对catchError的调用,该调用将侦听器包装起来并记录错误,并使用修改后的函数:

To adapt it to your needs, you may replace the call to catchError, which wraps the listener to catch and log errors, and use the modified function:

var appendScript = function(parent, scriptElt, listener) {
    // append a script element as last child in parent and configure 
    // provided listener function for the script load event
    //
    // params:
    //   parent - (DOM element) (!nil) the parent node to append the script to
    //   scriptElt - (DOM element) (!nil) a new script element 
    //   listener - (function) (!nil) listener function for script load event
    //
    // Notes:
    //   - in IE, the load event is simulated by setting an intermediate 
    //     listener to onreadystate which filters events and fires the
    //     callback just once when the state is "loaded" or "complete"
    //
    //   - Opera supports both readyState and onload, but does not behave in
    //     the exact same way as IE for readyState, e.g. "loaded" may be
    //     reached before the script runs.

    var safelistener = function(){
      try {
        listener();
      } catch(e) {
        // do something with the error
      }
    };

    // Opera has readyState too, but does not behave in a consistent way
    if (scriptElt.readyState && scriptElt.onload!==null) {
      // IE only (onload===undefined) not Opera (onload===null)
      scriptElt.onreadystatechange = function() {
        if ( scriptElt.readyState === "loaded" || 
             scriptElt.readyState === "complete" ) {
          // Avoid memory leaks (and duplicate call to callback) in IE
          scriptElt.onreadystatechange = null;
          safelistener();
        }
      };
    } else {
      // other browsers (DOM Level 0)
      scriptElt.onload = safelistener;
    }
    parent.appendChild( scriptElt );
};

这篇关于动态脚本加载同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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