How can I find the script element associated with the currently running script? I'm only interested in scripts inside the body of the document, not in the head (or elsewhere).
Here is what I have so far, it seems to work alright. Are there any possible pitfalls I'm not thinking of?
function getCurrentScriptElement() {
var placeholderId = 'placeholder-' + Math.random(),
script, placeholder;
document.write('<br id="' + placeholderId + '">');
placeholder = document.getElementById(placeholderId);
script = placeholder.previousSibling;
placeholder.parentNode.removeChild(placeholder);
return script;
}
The use case I have in mind for this involves scripts that need to inject content at the same place in the document where the script tag occurs, so delayed loading will not be an issue. In other words I will only be calling this function in places where it's appropriate, it's not going to be exposed as part of an API or anything.
I'm also aware of the problem with document.write
and XHTML, and am not worried about it in this case (so far).
My previous attempt looked something like this:
function getCurrentScriptElement() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
}
But, as we see in this question, this could easily fail if another script has been injected into the document.
I also found document.currentScript
in this WHATWG spec. It doesn't seem to be widely supported at this point. There's an interesting shim for document.currentScript
that takes another route... The script triggers an error, catches it, inspects the stack trace to find the URL of the script, and then finds the script element with the matching src
attribute.
It's a clever solution, but it apparently won't work in IE, and it would break if several scripts use identical URLs.
Ideally, I would like to find a solution that gives the same result as the top code sample (no extra requirements), but doesn't rely on document.write
. Is this possible? If not, is this code fairly safe assuming it's used correctly (only during page load, not XHTML)?
Edit: See this answer for another potential use case, and details on why a br
element is used for the placeholder.