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

How to Find the Script Tag That Loaded the Current Script?

Patricia Arquette
Release: 2024-12-17 01:10:26
Original
423 people have browsed it

How to Find the Script Tag That Loaded the Current Script?

How to Reference the Loading Script Tag

In various scenarios, it becomes necessary to reference the script tag that loaded the currently executing script. This can be achieved through multiple methods, each with its own advantages and drawbacks.

1. document.currentScript

<script><br>var me = document.currentScript;<br></script><br>

Benefits:

  • Simple and explicit.
  • Reliable.
  • Works with asynchronous scripts.
  • No need to modify the script tag.

Problems:

  • Not supported in older browsers and IE.
  • Doesn't work with modules (

    function isMe(scriptElem){</p>
    <div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">if( isMe(scripts[i])){
      me = scripts[i];
    }
    Copy after login
Copy after login

}

Benefits:

  • Flexible, can use previous techniques.

Problems:

  • Can be inefficient.

6. Last Executed Script

<script><br>var scripts = document.getElementsByTagName( 'script' );<br>var me = scripts[ scripts.length - 1 ];<br></script><br>

Benefits:

  • Simple.

Problems:

  • Doesn't work with asynchronous or dynamically inserted scripts.

The above is the detailed content of How to Find the Script Tag That Loaded the Current Script?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Previous article:How Can I Measure Internet Speed Using JavaScript? Next article:What Does the "..." (Spread Syntax) Do in React JSX?
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
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template