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
. 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
in the completely rendered page. Note that the id tag is not a valid attribute for
, 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.