Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.currentScript is null

Tags:

Browser is Chrome, document.currentScript should be supported but

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) 
Error :  1.js:4 Uncaught TypeError: Cannot read property 'src' of null 
like image 224
zloctb Avatar asked Aug 04 '16 13:08

zloctb


2 Answers

document.currentScript only returns the script that is currently being processed. During callbacks and events, the script has finished being processed and document.currentScript will be null. This is intentional, as keeping the reference alive would prevent the script from being garbage collected if it's removed from the DOM and all other references removed.

If you need to keep a reference to the script outside of any callbacks, you can:

var thisScript = document.currentScript;  setInterval(() => console.log(thisScript.src), 2000); 
like image 83
Andy E Avatar answered Sep 22 '22 13:09

Andy E


You can keep the reference of document.currentScript outside the callback

var currentScript = document.currentScript;  setInterval(function(){     var fullUrl = currentScript.src;     console.log(fullUrl) },2000); 
like image 43
Olivier Boissé Avatar answered Sep 26 '22 13:09

Olivier Boissé