2012-02-24 37 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