JavaScript: get the current executing <script> node? [duplicate]
I need to know if it is possible to obtain the current execution node?
Example:
..html
<script id="x">
console.log(document.currentNode.id); // << this must return "x"
</script>
..html
Thanks!
Modern browsers support a standard property on document object that points to the current script node:
https://developer.mozilla.org/en-US/docs/DOM/document.currentScript
<script id="x">
console.log(document.currentScript.id); // << this must return "x"
</script>
I don't know for 100% sure, but the collection of script tags returned by document.getElementsByTagName('script')
should not include the script tags that are below the presently executing <script>
. In other words, I think that this should work:
var arrScripts = document.getElementsByTagName('script');
var strScriptTagId = arrScripts[arrScripts.length - 1].id;
This will only work for scripts that are executing as the page loads. If this executes in a deferred script or as part of a page-load event, it will likely always report the last <script>
in the completely rendered page. Note that the id tag is not a valid attribute for <script>
, so your page won't likely validate. If you have any external scripts that write script tags (for example, third party ads), I think the code will be unpredictable. I played with this idea a couple years ago and the results were unsatisfactory.
Andrews Answer already has been a good idea but I experienced all the issues mentioned. This is why I choosed a different approach which works well for IE,FF and Chrome.
Simply executing the script in an onload event of an image. Defining a transparent 1pixel gif inline and you will receive "this" when it fires.
This example is used to change DIV content dynamically while rendering. My target is to fill the div with a different innerHTML created by an browser based xsl rendering (not shown here).
For sure you even can load any image from the internet so it must not be inline. And the big benefit: the image and its event are replacing themself with the new content so even the image will disappear. The "div" even does not need any "id" assignment.
<div id="demo">
empty
<img onLoad="changeNodeOnTheFly(this,'hurra');void(0);" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="/>
</div>
The script:
<script>
function changeNodeOnTheFly(ele, text)
{
ele.parentNode.innerHTML=text;
}
</script>
BR Heiko
Use document.write to find your position:
<script data-foo="bar">
var id = 'placeholder-' + Math.floor(Math.random() * 1e10)
document.write('<div id=' + id + '></div>')
var placeholder = document.getElementById(id)
var script = placeholder.previousSibling
placeholder.parentNode.removeChild(placeholder)
// "bar" is written to the document
document.write(script.getAttribute('data-foo'))
</script>
Why not use:
<script id="x">
console.log(document.getElementById("x").id);
</script>
精彩评论