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
Release: 2024-12-20 12:44:25
Original
690 people have browsed it

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;
Copy after login

2. Selecting Script by ID:

Add an id attribute to the script.

<script>
Copy after login

Obtain the element with document.getElementById().

var me = document.getElementById('myScript');
Copy after login

3. Selecting Script by Data Attribute:

Add a data-* attribute to the script.

<script data-name="myScript"></script>
Copy after login

Obtain the element with document.querySelector().

var me = document.querySelector('script[data-name="myScript"]');
Copy after login

4. Selecting Script by Source:

<script src="//example.com/embed.js"></script>
Copy after login

In embed.js:

var me = document.querySelector('script[src="//example.com/embed.js"]');
Copy after login

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";
}
Copy after login

6. Getting the Last Executed Script:

var scripts = document.getElementsByTagName('script');
var me = scripts[scripts.length - 1];
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template