0
0

処理を実行しているscript要素を取得する

Posted at

Document.currentScriptプロパティは現在処理中の<script>要素を取得します。値はHTMLScriptElementまたはnullとなります。
サンプルコードを書いてみます。下記のコードは、カウントアップ処理をHTML上に記述したものです。処理に関係のない記述は省略しています。

<div class="countUp"></div>

<script>
    const countUp = document.querySelector('.countUp');
    let n = 0;
    setInterval(() => {
        countUp.textContent = n++;
    }, 1000);
      
    console.log(document.currentScript);
</script>

ログの出力は以下になります。

<script>
    const countUp = document.querySelector('.countUp');
    let n = 0;
    setInterval(() => {
    countUp.textContent = n++;
    }, 1000);
      
    console.log(document.currentScript);
</script>

次はheadタグにscriptタグを挿入し読み込んだ場合です。JavaScriptファイルの処理内容は上のコードと同じです。

<head>
    <script src="./js/script.js" defer></script>
</head>
<script src="./js/script.js" defer></script>

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0