2013-08-19 76 views
3

當簡單地用<script />標籤加載腳本,您可以檢索腳本URL是這樣的:如何使用RequireJS獲取腳本URL?

var scriptURL = Array.prototype.pop.call (  // get the last... 
     document.getElementsByTagName ('script') // ...script tag on the page... 
    ).src.split ('?') [0];      // ...take 'src' attribute... 
               // ...and strip the query string 

這是一個黑客位的,但可以是非常有用的,有時,出於多種原因(例如,當腳本依賴於其他資源文件並且不想硬編碼路徑時)。它的工作原理是,在執行時,頁面上現有的最後一個<script />標籤就是您的腳本。

我不確定是否如此是當加載腳本與RequireJS。在RequireJS中是否有類似的方式從模塊定義中檢索腳本URL?

回答

7

您可以要求module模塊,常用來傳遞特殊config設置:

define(['module'], function (module) { 
    console.log(module) 
} 

這會給你的物體保持ID和URI到模塊

1

要獲得當前模塊的URL,您可以在requirejs中使用以下腳本。

define([module/hello], function (hello) { 
    var currentUrl = location.href; 
    var moduleUrl = url+require.toUrl("module/hello.js"); 
    alert(moduleUrl); 
}); 
相關問題