My colleague raised a question: How can I obtain the current file name in the JavaScript file dynamically inserted in the browser? Background
My colleague raised a question: How can I obtain the current file name in the JavaScript file dynamically inserted in the browser?
In addition to a file name output by the server, the following three methods should be obtained in the script.
Solution
The general solution can only be used for page static scripts label introduction or single dynamic loading.
The Code is as follows:
Var scripts = document. getElementsByTagName ('script ');
Var filename = scripts [scripts. length-1]. src;
Dynamically insert multiple script tags:
The Code is 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 on FireFox:
The Code is as follows:
Try {
Throw new Error ();
}
Catch (exception ){
Console. log (exception. fileName );
}
Solution C
My solution, operation source code:
The Code is as follows:
RequireScript ('A. js? '+ Date. now (), function (text, src ){
Console. log ('text: ', text );
GlobalEval ('(function () {\ nvar _ filename = "' + src + '"; \ n' + text +' \ n ;})();');
})
Browser output:
The Code is 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
Advantages: reliability, caching, deferred execution, and scalability.
Restriction: 1) variable naming is agreed as "_ filename"; 2) Same-source policy.
I also thought of this loading policy to load popular CoffeeScript, such:
The Code is 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