How May I Reference the Script Tag That Loaded the Currently-Executing Script

Get the current script tag

I think you could safely do this, and not in a DOM-ready mode.

var scripts = document.getElementsByTagName("script"),
selfScript = scripts[scripts.length-1];

I would suggest that if you can, put any configurations in another script block.

<script>
window.attr1 = 'val1';
window.attr2 = 'val2';
window.attr3 = 'val3';
</script>
<script src="x.js"></script>

jQuery Select current script tag

Outside the document ready method, just do $('script').last();:

<script type="text/javascript">
var currentScript = $('script').last();
$(document).ready( function(){
//Use the variable currentScript here
})
</script>

Or simply give an id to your script.

Get DOM element where script tag is

At the time the script is run, the document is only partially loaded. So your script element would be the last node in the document:

var target = document.documentElement; // start at the root element
while (target.childNodes.length && target.lastChild.nodeType == 1) { // find last HTMLElement child node
target = target.lastChild;
}
// target is now the script element
alert(target.parentNode); // this is p

How do I get a parent element of script tag in javascript?

In the script test.js you can use:

scriptParent = document.currentScript.parentElement;

or you can use other solutions from How may I reference the script tag that loaded the currently-executing script?
and add .parentElement to it.



Related Topics



Leave a reply



Submit