How to obtain the script element that loaded the script that is currently executing? This is required to dynamically load scripts into the DOM without the need for accessing the HEAD tag.
1. Using document.currentScript:
This method returns the <script> element whose code is being executed.
var me = document.currentScript;
2. Selecting Script by ID:
Add an id attribute to the script.
<script>
Obtain the element with document.getElementById().
var me = document.getElementById('myScript');
3. Selecting Script by Data Attribute:
Add a data-* attribute to the script.
<script data-name="myScript"></script>
Obtain the element with document.querySelector().
var me = document.querySelector('script[data-name="myScript"]');
4. Selecting Script by Source:
<script src="//example.com/embed.js"></script>
In embed.js:
var me = document.querySelector('script[src="//example.com/embed.js"]');
5. Looping Through All Scripts:
var me = null; var scripts = document.getElementsByTagName("script"); for (var i = 0; i < scripts.length; ++i) { if (isMe(scripts[i])) { me = scripts[i]; } } function isMe(scriptElem) { return scriptElem.getAttribute('src') === "//example.com/embed.js"; }
6. Getting the Last Executed Script:
var scripts = document.getElementsByTagName('script'); var me = scripts[scripts.length - 1];
The above is the detailed content of How to Find the Script Element that Loaded the Current Script?. For more information, please follow other related articles on the PHP Chinese website!