2014-07-04 31 views
0

如果不存在,加載angularjs文件是否可能?我正在製作一個基於Angular的小部件,並希望客戶端能夠使用該小部件。 如果角色不在主機頁面上,則不會加載腳本。加載角度如果不存在

我是Angular的新手,我很想學習(掌握)這個驚人的框架。

我發現我想要的jQuery變體。如果有人有段或網站,他可以參考我的(更好的)角度版本,它會幫助我很多

下面是代碼:

<script type="text/javascript"> 
    (function() { 

    // Localize jQuery variable 
    var jQuery; 
    /******** Load jQuery if not present *********/ 
    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') { 
     var script_tag = document.createElement('script'); 
     script_tag.setAttribute("type","text/javascript"); 
     script_tag.setAttribute("src", 
      "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"); 
     if (script_tag.readyState) { 
      script_tag.onreadystatechange = function() { // For old versions of IE 
       if (this.readyState == 'complete' || this.readyState == 'loaded') { 
        scriptLoadHandler(); 
       } 
      }; 
     } else { // Other browsers 
      script_tag.onload = scriptLoadHandler; 
     } 
     // Try to find the head, otherwise default to the documentElement 
     (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag); 
    } else { 
     // The jQuery version on the window is the one we want to use 
     jQuery = window.jQuery; 
     main(); 
    } 
    /******** Called once jQuery has loaded ******/ 
function scriptLoadHandler() { 
    // Restore $ and window.jQuery to their previous values and store the 
    // new jQuery in our local jQuery variable 
    jQuery = window.jQuery.noConflict(true); 
    // Call our main function 
    main(); 
} 
    /******** Our main function ********/ 
    function main() { 
     jQuery(document).ready(function($) { 
      // We can use jQuery 1.4.2 here 
     }); 
    } 

    })(); // We call our anonymous function immediately 
    </script> 

預先感謝您

+2

你可以做到這一點非常相似的方式,但做一次檢查按@Chankey帕塔克然後在'scriptLoadHandler()'你會ahve通過手動自舉文件'angular.bootstrap(文檔處理的角度,[ 'yourAppName'])' – maurycy

回答

1
if(typeof angular == 'undefined') { 
    //angular is not loaded correctly, deal with it here 
} 
+1

謝謝。這是我使用的代碼(用於測試它是否有效): 'var angular; if(typeof window.angular ==='undefined'){ console.log('load angular'); } else { console.log('loaded'); }' –

1

我會建議你使用yepnop.js它可能是類似的東西:

if(!angular) { 
yepnope([{ 
     load: 'http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js', 
     complete: function() { 
     if (!angular) { 
      yepnope('local/angular.min.js'); 
     } 
     } 
    }]); 
} 

你也可以設置它下載cdn文件,如果沒有加載然後嘗試一個本地版本。

+0

Yepnope看起來非常方便,謝謝你的參考。但是我正在製作一個小部件,所以我想盡可能地加載儘可能少的庫。 –

0

也許requireJs是一個選項。

require(["local/angular.min.js"], function() { 
    //todo your code here. 
});