-
-
Save ambar/1088730 to your computer and use it in GitHub Desktop.
如何在浏览器中动态插入的 JavaScript 文件中获取当前文件名?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var scripts = document.getElementsByTagName('script'); | |
console.log('a.js',' >>> ',scripts[scripts.length -1].src); | |
console.log(__filename); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>demo</title> | |
</head> | |
<body> | |
<!-- <script src="b.js" id="b"></script> --> | |
<script type="text/javascript"> | |
var globalEval = function(scriptText){ | |
var doc = document,s = doc.createElement('script'); | |
s.appendChild(doc.createTextNode(scriptText)); | |
doc.body.appendChild(s); | |
} | |
var _requireScripts = {}; | |
var requireScript = function(src,callback) { | |
if(typeof callback !== 'function'){ | |
callback = function() {} | |
} | |
if(_requireScripts[src]){ | |
callback(_requireScripts[src],src) | |
return; | |
} | |
get(src,function() { | |
callback(_requireScripts[src] = this.responseText||'',src) | |
}) | |
} | |
var get = function(url,callback) { | |
var xhr = new XMLHttpRequest(); | |
if(typeof callback !== 'function'){ | |
callback = function() {} | |
} | |
xhr.onload = callback.bind(xhr); | |
xhr.open('GET',url); | |
xhr.send(null); | |
} | |
/*var loadScript = function(src,callback) { | |
var s = document.createElement('script'); | |
if(typeof callback !== 'function'){ | |
callback = function() {} | |
} | |
if(s.readyState){ | |
s.onreadystatechange = function() { | |
if( s.readyState === 'loaded' || s.readystate === 'complete'){ | |
s.onreadystatechange = null | |
callback(); | |
} | |
} | |
}else{ | |
s.onload = callback; | |
} | |
s.src = src; | |
document.body.appendChild(s); | |
} | |
loadScript('b.js?param=1') | |
loadScript('a.js?param=2') | |
loadScript('b.js?param=3') | |
loadScript('a.js?param=4')*/ | |
requireScript('a.js?'+Date.now(),function(text,src) { | |
// console.log('text:',text); | |
globalEval('(function() { \nvar __filename = "'+ src +'";\n'+ text +'\n;})();'); | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
应用1