SAM said:
dhtml a écrit :
SAM said:
laredotornado a écrit :
If I have this include on my HTML page
<script type="text/javascript" src="scripts/myScript.js"></script>
How, from within "myScript.js" can I refer to the path of myself? In
other words, I would like to store in a variable the path WEBROOT/
scripts/myScript.js.
var myPath = document.getElementsByTagName('script')[0].src;
Maybe:
with in first script's tag of my tested file
src="test.js"
and file 'test.js' with :
alert(document.getElementsByTagName('script')[0].src);
that works (in my Firefox) as attempted
var scripts = document.getElementsByTagName('script'),
thisScript = scripts[scripts.length-1].src || location.href;
But that would only work while the script was loading.
of corse !
it's why it has to be in 1st position
It would not work if the script inserted other scripts before that
line of code. It would not be reliable in the jquery.ready function,
or window.onload or any other function that was called after the
script had loaded.
??
I'm sensing some incredulousness in those question marks
This is a technique of John Resig discussed, and in his example, used
the jQuery.ready function, which would cause the problems. It was posted
on Ajaxian. Steve Sauders stopped by to plug his own use of the approach:-
http://ejohn.org/blog/degrading-script-tags/
Unless there is a defer attribute, scripts.length-1 will be the current
script. But that won't work in onload or jQuery.ready.
window.onload = function() {
alert(document.getElementsByTagName('script')[0].src);
}
in next script of my tested file works too
But if the there was a desire to reference the current script, and that
script was not the 0th script in the source order, it won't work. That
was why I had:-
script = scripts[scripts.length-1] || location.href;
But that would have mixed results with defer attribute, wouldn't it? And
wouldn't work if the script in question had:
appendChild(makeNewScriptTag('foo.js'));
- because then script.length - 1 would be the one that got appended.
and it does too with in the body :
<a href="javascript:alert(document.getElementsByTagName('script')[0].src)">
path</a>
Only when the position is determined, not by taking the last one.
Yes ! what to do with a such info ?
I have no idea why anyone would want to write buggy code taht solves no
problems, and then attempt to create a problem to justify the code.
Garrett