JS動態 按需 加載

現在想做這麼一件事:

       在創建類之前,動態的添加其資源,且添加一次。

       在頁面load前,所謂的動態按需加載有:

        document.wrieln(js標籤和路徑);        document.appendChild(js對象);  等等...並非我想要.


      

HQ.loadJSFile = function(className){//單一文件加載,可多個擴展
      var xhr = null,obj = null,status = null;
      
      if(loadClassManager[className]){
      return loadClassManager[className];
      } 
      var fileName = className.replace(/\./g,"/"),js = doc.createElement('SCRIPT'),head = doc.getElementsByTagName('head')[0];
 js.src = fileName+".js?"+(+new Date());
 js.charset = "utf-8";
 js.type = "text/javascript";
     if(head){head.appendChild(js);}else{throw '該頁面必須包含head標籤元素!!';}
      
      try {
      if (typeof XMLHttpRequest != 'undefined') {//Ajax請求
      xhr = new XMLHttpRequest();
      } else {
      xhr = new ActiveXObject('Microsoft.XMLHTTP');
      }
             xhr.open('GET', fileName+".js?dt="+(+new Date()), false);//同步
             xhr.send(null);
             status = xhr.status;
             if ((status >= 200 && status < 300) || (status === 304)){//FireFox下通過 
               var classes = className.split(".");
     var hq = null;
     try{
      for(var i=0,len = classes.length;i<len;i++){
      if(i==0){
      hq = HQ;
      }else{
      hq = hq[classes[i]];
      }
      }
    }catch(e){
       throw e.message;
       }
              obj = new hq();
          loadClassManager[className] = obj; 
             }
         } catch (e) {
          throw e.message;
         }
         return obj;
    };
以上在火狐下驗證,時而成功,其他瀏覽器均失敗. 

思路是這樣的:

        將文件以ajax同步的形式加載進來,同時先將對應的資源添加到頁面.最後動態的new一個對象 裏面是爲了測試,並且返回了這個對象。

記錄與此,希望有相同需求的將思路分享下,我在尋去解決辦法。



發佈了95 篇原創文章 · 獲贊 14 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章