JavaScript: get the current executing <script> node?

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.

Tags:

Javascript

Dom