Reputation: 50328
Say I have a reference to a javascript file:
<script type="text/javascript" src="http://blah.com/js/count.js"></script>
with the contents of count.js:
alert("This script is loading from:" + url);
How do I identify the value that should go into the url variable, from inside of count.js?
Upvotes: 0
Views: 148
Reputation: 4686
When an external script is being executed, its SCRIPT
element would be the last one in the page, which is document.scripts[document.scripts.length-1]
.
So, if the SCRIPT
element is:
<script type="text/javascript" src="http://blah.com/js/count.js"></script>
And the count.js
file contents is:
alert("This script is loading from:" + document.scripts[document.scripts.length-1].src);
It'll display:
This script is loading from: http://blah.com/js/count.js
Note that HTML5 introduces an async
attribute for SCRIPT
element, which likely make the above method useless. In case of asynchronous, the only way to get the associated SCRIPT
element is to use Gecko's (Firefox) document.currentScript
, but this is non standard and is not implemented by all other web browser engines. i.e.: Trident (MSIE), WebKit (Chrome/Safari), Presto (Opera).
Upvotes: 1