Home >Web Front-end >JS Tutorial >How to Find the Script Element that Loaded the Current Script?

How to Find the Script Element that Loaded the Current Script?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 12:44:25685browse

How to Find the Script Element that Loaded the Current Script?

How to Reference the Script Tag that Loaded the Current Script

Problem

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.

Answer

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn