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
Patricia ArquetteOriginal
2024-12-17 01:10:26542browse

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>
    <pre class="brush:php;toolbar:false">if( isMe(scripts[i])){
      me = scripts[i];
    }

    }

    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!

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