Javascript get script by src

How might I get the script filename from within that script?

I’m pretty sure the answer is no, but thought I’d ask anyway. If my site references a scripted named «whatever.js», is it possible to get «whatever.js» from within that script? Like:

var scriptName = . if (typeof jQuery !== "function") < throw new Error( "jQuery's script needs to be loaded before " + scriptName + ". Check the tag order."); > 

Since you are going to be typing that line into the file somewhere, couldn’t you just type in the name of the file you’re adding it to?

Heh, if someone wants to submit «fuss less» and that gets a couple upvotes, I’d accept that as the answer. 😀

Specifying ‘var scriptName = . ‘ inside each script probably isn’t the greatest idea. The way you are declaring it, scriptName is a global variable. It would work better if you used closures. jibbering.com/faq/faq%5Fnotes/closures.html

The other advantage to this is if you want to get the full URL-path to the running script. Not all .js files are served from the same domain as the html pages that use them.

12 Answers 12

var scripts = document.getElementsByTagName('script'); var lastScript = scripts[scripts.length-1]; var scriptName = lastScript.src; alert("loading: " + scriptName); 

Tested in: FF 3.0.8, Chrome 1.0.154.53, IE6

See also: How may I reference the script tag that loaded the currently-executing script?

Edge case: If the current script was added to after is loaded and there are any scripts in this will return the last script in the , not the currently running script that’s in .

Читайте также:  Задача 3 файлы python

I have come across a case where this algorithm doesn’t work reliably. Other script tags that are set to async can run between your script being requested and run. These scripts can add other scripts to the DOM which appear after yours. When your script run the last script on the page is no longer yours and the wrong src is returned.

This answer is seriously out of date. Scripts can be deferred, async, modules, workers. This answer works in none of them.

I feel like document.currentScript should be mentioned here, but like @gman said this answer is out of date overall and the algorithm does not cover many edge cases.

I’m aware this is old but I have developed a better solution because all of the above didn’t work for Async scripts. With some tweaking the following script can cover almost all use cases. Heres what worked for me:

Not sure about support on Internet Explorer, but works fine in every other browser I tested on.

Thanks! Exactly what I was looking for! Interesting that sometimes the same approach with error’s stack appears in python or Java code.

Thanks! that’s a great approach as it works also in Web Workers. However it fails after minification because the function is not called getScriptName anymore. The solution is to replace the currentStackFrameRegex expression with: new RegExp(arguments.callee.name + ‘ \(.+\\/(.*):\\d+:\\d+\)’)

@MaMazav arguments.callee.name won’t work If the function is defined as a function expression. I think the catch-all solution would be replacing arguments.callee.name with scriptName where scriptName is var scriptName = arguments.callee.name || ‘getScriptName’; . Of course, minification would change the variable name if the function expression is assigned to a normal variable, so one would have to assign the function to an object key to make this work.

var scripts = document.getElementsByTagName("script"), currentScriptUrl = (document.currentScript || scripts[scripts.length - 1]).src; 

currentScript() is supported by all browsers except IE.

Make sure it’s ran as the file is parsed and executed, not on DOM ready or window load.

If it’s an empty string, your script block has no or an empty src attribute.

Источник

How to get the location (src) of a javascript file?

How can the code in howdy.js know about http://mysite.com/scripts/howdy.js ? Edit: Clarification. I cannot rely on searching the DOM for my script tag because I need to know about it before the DOM may be ready.

@tenfour — There are other scripts that howdy.js may pull in from the same directory and I can’t be certain where howdy.js will be hosted (test, prod, qa, client host, etc). It’s not awesome but it is a business requirement. @Marcel — Yes, you are right, It is a dup. But I’ll leave it up as I couldn’t find that answer with the search terms I used.

4 Answers 4

In the moment in which the current script is being executed, will be the last script element in the DOM, therefore you can get it by:

var scripts = document.getElementsByTagName('script'), currentScriptSrc = scripts[scripts.length-1].src; 

Check this example that loads this script.

Edit: Taking in consideration the @kangax’s comment, about the async and defer attributes, the only safe way IMO, previously knowing the file name, would be to inspect the script elements on the page, examining its src attribute, some libraries like Scriptaculous.us use this technique, for example:

var scripts = document.getElementsByTagName('script'), len = scripts.length, re = /howdy\.js$/, src, howdyScriptSrc; while (len--) < src = scripts[len].src; if (src && src.match(re)) < howdyScriptSrc = src; break; >> ​ 

Источник

Получить контент внешнего js скрипта

Возможно ли в каком-либо браузере (Chrome, Firefox) получить содержимое внешнего тега c помощью javascript?

Пример: На сайте one.com встроен тег следующего вида

Not "should break", but "are breaking"; I saw that happen. Pages look faster if javascripts load asynchronously by default. It could break functionality, yes, but in most cases it probably doesn't. And those race conditions can and are identified and handled while loading by most recent js engines. @MarcoDemaio

I have come across a case where this algorithm doesn't work reliably. Other script tags that are set to async can run between your script being requested and run. These scripts can add other scripts to the DOM which appear after yours. When your script run the last script on the page is no longer yours and the wrong src is returned.

For recent browsers, you can use document.currentScript to get this information.

var mySource = document.currentScript.src; 

The upside is that it's more reliable for scripts that are loaded asynchronously. The downside is that it's not, as best I know, universally supported. It should work on Chrome >= 29, FireFox >= 4, Opera >= 16. Like many useful things, it doesn't seem to work in IE.

When I need to get a script path, I check to see if document.currentScript is defined, and, if not, use the method described in the accepted answer.

if (document.currentScript) < mySource = document.currentScript.src; >else < // code omitted for brevity >

caniuse.com doesn't monitor this feature yet. You can help with an upvote here: github.com/Fyrd/caniuse/issues/1099.

As it appears in source (e.g. /js/main.js ), this is cross-browser:

var scriptSource = (function() < var scripts = document.getElementsByTagName('script'), script = scripts[scripts.length - 1]; //No need to perform the same test we do for the Fully Qualified return script.getAttribute('src', 2); //this works in all browser even in FF/Chrome/Safari >()); 

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

After some tests it seems hard to get the fully qualified one in a cross-browser way. The solution suggested by Crescent Fresh does not work in IE8 to get the fully qualified, even if it works in IE7

This method work with defer, async and lazy loading Since you know the filename of your script, and if it will be unique

/* see * http://stackoverflow.com/questions/984510/what-is-my-script-src-url/984656#984656 * http://www.glennjones.net/Post/809/getAttributehrefbug.htm * * iterate all script to find script with right filename * this work with async and defer (but your script MUST have a unique filemane) * mozilla support document.currentScript and we use it, if is set * * this will not work with local script loaded by jQuery.getScript(), * since there is no script tag added into the dom. the script is only evaluated in global space. * http://api.jquery.com/jQuery.getScript/ * * to fix this odd, you can add a reference in meta ( meta[name=srcipt][content=url] ) * when you load the script */ var scriptFilename = 'jquery.plugins.template.js'; // don't forget to set the filename var scriptUrl = (function() < if (document.currentScript) < // support defer & async (mozilla only) return document.currentScript.src; >else < var ls,s; var getSrc = function (ls, attr) < var i, l = ls.length, nf, s; for (i = 0; i < l; i++) < s = null; if (ls[i].getAttribute.length !== undefined) < s = ls[i].getAttribute(attr, 2); >if (!s) continue; // tag with no src nf = s; nf = nf.split('?')[0].split('/').pop(); // get script filename if (nf === scriptFilename) < return s; >> >; ls = document.getElementsByTagName('script'); s = getSrc(ls, 'src'); if ( !s ) < // search reference of script loaded by jQuery.getScript() in meta[name=srcipt][content=url] ls = document.getElementsByTagName('meta'); s = getSrc(ls, 'content'); >if ( s ) return s; > return ''; >)(); var scriptPath = scriptUrl.substring(0, scriptUrl.lastIndexOf('/'))+"/"; 

note: this will not work with local script loaded by jQuery.getScript(), since there is no script tag added into the dom. the script is only evaluated in global space. http://api.jquery.com/jQuery.getScript/

to fix it you can do something like:

function loadScript(url,callback) < if ( $('[src="https://stackoverflow.com/questions/984510/'+url+'"]').length ) return true; // is already loaded // make a reference of the loaded script if ( $('meta[content="'+url+'"]', $("head")).length ) return true; // is already loaded var meta = document.createElement('meta'); meta.content = url; meta.name = 'script'; $("head").append(meta); return $.ajax(< cache: true, url: u, dataType: 'script', async: false, success : function (script) < try < if ( typeof callback == 'function' ) callback(); >catch (error) < //console.log(error); >> >); > 

Источник

Оцените статью