Background
A colleague raised the question of how to get the current file name in a JavaScript file that was dynamically inserted in the browser.
In addition to the server output a filename, there should be only the following three ways to get it in the script.
Solution A
The universal solution can only be used for page static scripts tag introduction or single dynamic loading.
Copy Code code as follows:
var scripts = document.getelementsbytagname (' script ');
var filename = scripts[scripts.length-1].src;
To dynamically insert multiple script labels:
Copy Code code as follows:
Loadscript (' B.js?param=1 ')
Loadscript (' a.js?param=2 ')
Loadscript (' b.js?param=3 ')
Loadscript (' a.js?param=4 ')
/* Output
A.js >>> http://localhost:800/io/a.js?param=4
A.js >>> http://localhost:800/io/a.js?param=4
B.js >>> http://localhost:800/io/a.js?param=4
B.js >>> http://localhost:800/io/a.js?param=4
*/
Solution B
Abnormal type, can only work in Firefox:
Copy Code code as follows:
try {
throw new Error ();
}
catch (Exception) {
Console.log (Exception.filename);
}
Solution C
My solution, the operation of the source code:
Copy Code code as follows:
Requirescript (' A.js? ') +date.now (), function (TEXT,SRC) {
Console.log (' text: ', text);
Globaleval (' (function () {\nvar __filename = ' + src + '; \ n ' + text + ' \ n;}) ();');
})
Browser output:
Copy Code code as follows:
<script> (function () {
var __filename = "a.js?1310971812334";
var scripts = document.getelementsbytagname (' script ');
Console.log (' a.js ', ' >>> ', scripts[scripts.length-1].src);
Console.log (__filename);
;}) ();</script>
Benefits: Reliable, cacheable, can be deferred, extensible.
Limit: 1 The variable name is specified as "__filename"; 2) homology policy.
And the idea that this load strategy is used to load popular coffeescript such as:
Copy Code code as follows:
Requirescript (' Script.coffee ', function (TEXT,SRC) {
if (Iscoffeescript (SRC))
Globaleval (Coffeescript.compile (text));
})
Link
Cross-origin Resource Sharing
Passing JavaScript arguments via the src attribute
Coffeescript
View or download
https://gist.github.com/1088730