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.Copy codeThe Code is as follows: var scripts = document. getElementsByTagName ('script ');
Var filename = scripts [scripts. length-1]. src;
Dynamically insert multiple script tags:Copy codeThe 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:Copy codeThe Code is as follows: try {
Throw new Error ();
}
Catch (exception ){
Console. log (exception. fileName );
}
Solution C
My solution, operation source code:Copy codeThe 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:Copy codeThe 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:
Copy codeThe 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