Document. currentScript Is Null

Document. currentScript Is Null

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

4 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);
4

document.currentScript will also be null if script was loaded as a module like this.

<script type="module" src="foo/bar.js"></script>

For modules, docs say import.meta.url should be used.

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);

You did not read the documentation, which says:

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.