JavaScript - How to Get the Url of Script Being Called

JavaScript - How do I get the URL of script being called?

From http://feather.elektrum.org/book/src.html:

var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];

The variable myScript now has the script dom element. You can get the src url by using myScript.src.

Note that this needs to execute as part of the initial evaluation of the script. If you want to not pollute the Javascript namespace you can do something like:

var getScriptURL = (function() {
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
return function() { return myScript.src; };
})();

How to get the currently loading script name and the url variable of the script?


Thanks for all your efforts I have made that working by assigning an id attribute in the script tag and accessed via jQuery,

<script src="test.js?id=12" id="myScript"></script>

var currentScript = $("#myScript").attr('src'); //This will give me my script src

Thanks,

Karthik

URL of current script in JavaScript

In JQuery you could do:

$('script').each(function(i, e) {
alert($(e).attr('src'));
});

Get the current URL with JavaScript?

Use:

window.location.href

As noted in the comments, the line below works, but it is bugged for Firefox.

document.URL

See URL of type DOMString, readonly.

What is my script src URL?

Put this in the js file that needs to know it's own url.

Fully Qualified (eg http://www.example.com/js/main.js):

var scriptSource = (function(scripts) {
var scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1];

if (script.getAttribute.length !== undefined) {
return script.src
}

return script.getAttribute('src', -1)
}());

Or
As it appears in source (eg /js/main.js):

var scriptSource = (function() {
var scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1];

if (script.getAttribute.length !== undefined) {
return script.getAttribute('src')
}

return script.getAttribute('src', 2)
}());

See http://www.glennjones.net/Post/809/getAttributehrefbug.htm for explanation of the getAttribute parameter being used (it's an IE bug).



Related Topics



Leave a reply



Submit