Html javascript src url

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

Inside «myscript.js», I want to get access to the URL «http://site2.com/myscript.js». I’d like to have something like this:

function getScriptURL() < // something here return s >alert(getScriptURL()); 

Based on your example URLs, you may want to note what behavior you’re expecting if the browser is set to block third party scripts.

10 Answers 10

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; >; >)(); 

Will this always return the URL of the right script though, in all browsers? This looks like it will return the last script tag, but what if the document has more than one script tag in it?

Ok. my question then becomes, do all browsers always fully load an execute the complete contents of a remote script before moving on to the next script tag? How rigorously is this standardized? I could imagine it happening in parallel.

Читайте также:  Image to ascii java

It is required that scripts run completely and in order because of what would happen if the script tag contained a document.write. This is the reason for the recommendations to put scripts at the bottom of the page because they will actually block other content from loading. That said, HTML5 modifies that with the use of the async and defer attributes: whatwg.org/specs/web-apps/current-work/multipage/…

This doesn’t work if you load the script after the page has loaded using something like this: document.getElementsByTagName(«head»)[0].appendChild(scriptElement);

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.

Everything except IE supports

A word of caution! it will not work if the loaded is script type is module. for more stackoverflow.com/questions/2976651/…

You can add id attribute to your script tag (even if it is inside a head tag):

and then access to its src as follows:

document.getElementById("myscripttag").src 

of course id value should be the same for every document that includes your script, but I don’t think it is a big inconvenience for you.

This answer should be marked as «accepted» as it covers the cases when you call the method not in the «global» script context or in «async» script, and it doesn’t depend on the browser implementation.

Note that .src can return an absolute path, even if a relative path was specified. You can use .getAttribute(‘src’)

Simple and straightforward solution that work very well :

If it not IE you can use document.currentScript
For IE you can do document.querySelector(‘script[src*=»myscript.js»]’)
so :

update

In a module script, you can use:

I wrote a class to find get the path of scripts that works with delayed loading and async script tags.

I had some template files that were relative to my scripts so instead of hard coding them I made created the class to do create the paths automatically. The full source is here on github.

A while ago I had use arguments.callee to try and do something similar but I recently read on the MDN that it is not allowed in strict mode.

function ScriptPath() < var scriptPath = ''; try < //Throw an error to generate a stack trace throw new Error(); >catch(e) < //Split the stack trace into each line var stackLines = e.stack.split('\n'); var callerIndex = 0; //Now walk though each line until we find a path reference for(var i in stackLines)< if(!stackLines[i].match(/http[s]?:\/\//)) continue; //We skipped all the lines with out an http so we now have a script reference //This one is the class constructor, the next is the getScriptPath() call //The one after that is the user code requesting the path info (so offset by 2) callerIndex = Number(i) + 2; break; >//Now parse the string for each section we want to return pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/); > this.fullPath = function() < return pathParts[1]; >; this.path = function() < return pathParts[2]; >; this.file = function() < return pathParts[3]; >; this.fileNoExt = function() < var parts = this.file().split('.'); parts.length = parts.length != 1 ? parts.length - 1 : 1; return parts.join('.'); >; > 

Источник

Javascript set img src

I am probably missing something simple but it’s quite annoying when everything you read doesn’t work. I have images which may be duplicated many times over the course of a dynamically generated page. So the obvious thing to do is to preload it and use that one variable as the source all the time.

var searchPic; function LoadImages() < searchPic = new Image(100,100); searchPic.src = "XXXX/YYYY/search.png"; // This is correct and the path is correct >
 document["pic1"].src = searchPic; 

However, the image is never set properly in FireBug when I query the image I get [object HTMLImageElement] as the src of the image In IE I get:

http://localhost:8080/work/Sandbox/jpmetrix/[object] 

10 Answers 10

You should be setting the src using this:

document["pic1"].src = searchPic.src; 

Pure JavaScript to Create img tag and add attributes manually ,

var image = document.createElement("img"); var imageParent = document.getElementById("body"); image.id = "id"; image.className = "class"; image.src = searchPic.src; // image.src = "IMAGE URL/PATH" imageParent.appendChild(image); 

Set src in pic1

document["#pic1"].src = searchPic.src; 
document.getElementById("pic1").src= searchPic.src; 

j-Query to archive this,

Also, one way to solve this is to use document.createElement and create your html img and set its attributes like this.

var image = document.createElement("img"); var imageParent = document.getElementById("Id of HTML element to append the img"); image.id = "Id"; image.className = "class"; image.src = searchPic.src; imageParent.appendChild(image); 

REMARK: One point is that Javascript community right now encourages developers to use document selectors such as querySelector , getElementById and getElementsByClassName rather than document[«pic1»].

Источник

Javascript function return src path

But it doesn’t seem to work. Anything I’m missing? Thanks to anyone pointing me in the right direction.

4 Answers 4

The src attribute takes an URL, not JavaScript. You might want to try

  

@2astalavista I do inline script only if it is trivial and deals only with the object, where it is noted. Everybody must find his own «red line» there.

The tag will first load the placeholder «pixel.gif», when finished, it will run the onload code, which loads another image. If you do not set onload to null, it will be called again after the second load, after the third load, .

You can’t do this. The src attribute of an img element can’t be interpreted as javascript when the html is interpreted.

 document.onload = function()< document.getElementById('someImage').src=getImagePath(); >; 

While I ofcourse see the point of avoiding inline script, I personally draw the line at a point, where an inline script exclusivly deals with the object, where it is noted. This keeps it readable and avoids the expensive getElementById(string) . Everybody has his own likings, though.

Building on Eugen’s answer, I wanted something self-contained (no id’s, as inline as possible) that would not require a hosted pixel.gif image. I came up with a few possibilities:

One option would be to use a base64 encoded src URL instead (as small as possible). Note that data-uris are supported in IE8+:

 

A second option would be to use document.write to write the image tag directly with an inline script. Just put the below instead of the . Note that many consider document.write to be bad practice:

  

A third (perhaps even more hackish) option would be to forcibly break the image by supplying a null src, and (ab)use the onerror callback.

This works in IE11 and Chrome, but not Firefox:

This fourth option relies on a simple function that sets an tag followed immediately by an inline that sets the image’s src via JavaScript:

 -->  
 --> function getImagePath() < return "https://www.gravatar.com/avatar/71ec7895cada78741057c644d858b0e3"; >function set_most_recent_img_src(val) 

Summary: I’m just ideating. Each option has different implications and requirements — they’re all workarounds, and should be tested thoroughly for your specific use case. Personally I think the first option (base64 URI) is the most solid (if you ignore old IE browsers, which I happily can).

Источник

What is my script src URL?

Is there a simple and reliable way to determine the URL of the currently-executing JavaScript file (inside a web page)? My only thought on this is to scan the DOM for all the script src attributes to find how the current file was referenced and then figure out the absolute URL by applying it to document.location . Anyone have other ideas, is there some super-easy method I completely overlooked? UPDATE: Script elements accessed via the DOM already have a src property which contains the full URL. I don’t know how ubiquitous/standard that is, but alternatively you can use getAttribute(«src») which will return whatever raw attribute value is in the [X]HTML.

Thanks to ie11 there doesn’t seem to be a water tight approach. See this site for some comparisons fractallambda.com/2014/11/15/…

6 Answers 6

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).

For the fully qualified one can’t you just use script.src? Why are you using script.getAttribute(‘src’, -1).

Great answer. One caveat — it the script is lazy loaded (injected into the DOM by another script), it won’t be the last script in the DOM, so this exact snippet won’t work.

Will certainly not work with

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); >> >); > 

Источник

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