How can I find the element associated with the currently running script?

emreder

New Member
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?\[code\]function getCurrentScriptElement() { var placeholderId = 'placeholder-' + Math.random(), script, placeholder; document.write('<span id="' + placeholderId + '"></span>'); placeholder = document.getElementById(placeholderId); script = placeholder.previousSibling; placeholder.parentNode.removeChild(placeholder); return script;}\[/code\]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 \[code\]document.write\[/code\] and XHTML, and am not worried about it in this case (so far).Closely related to this question.
 
Back
Top