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.
VaR scripts = Document. getelementsbytagname ('script'); var filename = scripts [scripts. Length-1]. SRC;
Dynamically insert multiple script tags:
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 = 4A. js> http: // localhost: 800/IO/a. js? Param = 4b. js> http: // localhost: 800/IO/a. js? Param = 4b. js> http: // localhost: 800/IO/a. js? Param = 4 */
Solution B
Abnormal type, can only work on Firefox:
Try {Throw new error ();} catch (exception) {console. Log (exception. filename );}
Solution C
My solutions and operationsSource code:
Requirescript ('A. js? '+ Date. now (), function (text, Src) {console. log ('text: ', text); globaleval (' (function () {\ nvar _ filename = "'+ SRC + '"; \ n' + TEXT + '\ n ;})();');})
Browser output:
<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:
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