2016-08-04 10 views
6

ブラウザはChromeです。 document.currentScriptはサポートされていますが、document.currentScript is null

index.htmlを

<link href="css/main.css" rel="stylesheet" /> 
<script src="1.js"></script> 
<style> 

1.js

setInterval(function(){ 


var fullUrl = document.currentScript.src; 

console.log(fullUrl) 
},2000) 

エラーする必要があります。 1.js:4キャッチされない例外TypeError:プロパティを読み取ることができませんの 'SRC' null

答えて

12

document.currentScriptreturns the script that is currently being processed。コールバックおよびイベント中に、スクリプトの処理が終了し、document.currentScriptnullになります。これは意図的なものです。参照を有効にしておくと、スクリプトがDOMから削除され、他のすべての参照が削除された場合にスクリプトがガベージコレクションされなくなります。

あなたはあなたができる、任意のコールバックの外にスクリプトへの参照を保持する必要がある場合:

var thisScript = document.currentScript; 

setInterval(() => console.log(thisScript.src), 2000); 
+1

ありがとう、良い答え。 – zloctb

+1

'thisScript'を隔離するためにこれをクロージャーで必ず実行してください。 – Campbeln

0

the documentationと表示されませんでした。

It's important to note that this will not reference the <script> element if the code in the script is being called as a callback or event handler; it will only reference the element while it's initially being processed.

+0

document.currentScriptの参照を保持することができます> ''それがそこにある – Brian

+1

@Brian:もう一度見てください。 –

2

あなたは、コールバック

var currentScript = document.currentScript; 

setInterval(function(){ 
    var fullUrl = currentScript.src; 
    console.log(fullUrl) 
},2000);