2016-08-04 15 views
6

Przeglądarka jest Chrome. document.currentScript powinny być wspierane, aledocument.currentScript ma wartość 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) 

Błąd: 1.js: 4 Uncaught TypeError: nie można odczytać właściwość 'źródło' z null

Odpowiedz

12

tylko returns the script that is currently being processed. Podczas wywołań zwrotnych i zdarzeń skrypt zakończył przetwarzanie, a document.currentScript będzie null. Jest to zamierzone, ponieważ zachowanie referencji przy życiu uniemożliwiłoby zbieranie skryptu, jeśli zostanie usunięte z DOM i usunięte zostaną wszystkie inne odniesienia.

Jeśli trzeba zachować odniesienie do skryptu poza wszelkimi callbacków można:

var thisScript = document.currentScript; 

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

dziękuję, dobra odpowiedź. – zloctb

+1

Pamiętaj tylko, aby zrobić to w zamknięciu, aby wyizolować 'ten skrypt'. – Campbeln

0

Nie przeczytałeś the documentation, która mówi:

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

> '' właśnie tam – Brian

+1

@Brian: Spójrz jeszcze raz. –

2

można zachować odniesienie document.currentScript poza zwrotnego

var currentScript = document.currentScript; 

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