2012-02-24 36 views
8

在我的ExtJS 4.0.7应用程序中,我有一些第三方JavaScript,我需要动态加载呈现某些面板内容(一些花哨的图表/可视化小部件)。我可以使用Ext的加载器来动态加载非ext脚本/对象吗?

我遇到了一个古老的问题,脚本在我尝试使用它之前没有完成加载。我认为ExtJS可能有一个优雅的解决方案(很像类加载器:Ext.Loader)。

我看过Ext.Loader和Ext.ComponentLoader,但都没有提供我正在寻找的东西。我是否必须“自己动手”并设置计时器以等待标记变量存在?

回答

5

我已经看了两个Ext.Loader和Ext.ComponentLoader,但既不 似乎提供什么我正在寻找

真的看起来这是真的。它可以帮助你在这里,我想,唯一的一点是装载机的injectScriptElement方法(其中,但是,是私人的):

var onError = function() { 
    // run this code on error 
}; 
var onLoad = function() { 
    // run this code when script is loaded 
}; 
Ext.Loader.injectScriptElement('/path/to/file.js', onLoad, onError); 

好像这种方法会做你想要的(这里是example)。但唯一的问题是,...你知道,该方法被标记为私人。

+0

- 尼斯找到!它的功能足够小,我可能只是“借”它:) – Brian 2012-02-24 16:27:08

0

从源头上看,在我看来,你可以做一些黑客的方式。尝试使用Ext.Loader.setPath()将虚假命名空间映射到第三方JavaScript文件,然后使用Ext.Loader.require()尝试加载它们。它看起来并不像ExtJS实际上检查是否在包含的文件中定义了所需的类。

+2

'它看起来不像ExtJS实际上检查是否需要class ...'。看起来像它真的。在'onFileLoaded'方法中会引发异常'“即使文件已经被加载,下面的类也不会被声明...”' – 2012-02-24 13:11:08

+0

错过了...... – Mchl 2012-02-24 13:18:06

1

为了你的Google在那里,我结束了借用一些分机代码我自己的滚动:

var injectScriptElement = function(id, url, onLoad, onError, scope) { 
     var script = document.createElement('script'), 
      documentHead = typeof document !== 'undefined' && (document.head || document.getElementsByTagName('head')[0]), 
      cleanupScriptElement = function(script) { 
       script.id = id; 
       script.onload = null; 
       script.onreadystatechange = null; 
       script.onerror = null; 

       return this; 
      }, 
      onLoadFn = function() { 
       cleanupScriptElement(script); 
       onLoad.call(scope); 
      }, 
      onErrorFn = function() { 
       cleanupScriptElement(script); 
       onError.call(scope); 
      }; 

     // if the script is already loaded, don't load it again 
     if (document.getElementById(id) !== null) { 
      onLoadFn(); 
      return; 
     } 

     script.type = 'text/javascript'; 
     script.src = url; 
     script.onload = onLoadFn; 
     script.onerror = onErrorFn; 
     script.onreadystatechange = function() { 
      if (this.readyState === 'loaded' || this.readyState === 'complete') { 
       onLoadFn(); 
      } 
     }; 
     documentHead.appendChild(script); 
     return script; 
    } 


var error = function() { 
    console.log('error occurred'); 
} 

var init = function() { 
    console.log('should not get run till the script is fully loaded'); 
} 

injectScriptElement('myScriptElem', 'http://www.example.com/script.js', init, error, this); 

11

下面是它是如何在做ExtJS 4.1.x一个例子:

Ext.Loader.loadScript({ 
    url: '...',     // URL of script 
    scope: this,     // scope of callbacks 
    onLoad: function() {   // callback fn when script is loaded 
     // ... 
    }, 
    onError: function() {   // callback fn if load fails 
     // ... 
    } 
}); 
+0

是的,我注意到这是4.1中的一个选项,很高兴看到Sencha认为它也有用。 – Brian 2013-02-05 06:47:13