0

I wrote the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="j1.js" **defer**></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Elderflower</title>
</head>
<body>
    <h1 class="target">Hii</h1>
    <h1>Unmodified</h1>
    <h1 class="target">Hii</h1>
</body>
</html>

and here's the javascript:

let el = document.querySelectorAll(".target");
for(let i=0;i<el.length;i++)
{
    el[i].innerText = "Modified by JS";
}

Why does my javascript not make modifications until I don't put the word defer in line 4 in html??

  • Defer tells the browser not to execute the script until after the page is done loading. When including a none deferred script it will pause the parsing of the document and execute the script, meaning you will only be able to select elements upto the point the script was parsed. So the solutions you could use would be to add a `defer` attribute, add the script to the end of the body, or attach a pageload event and execute your code there. – Brenden Sep 08 '20 at 19:52
  • @HanYolo Thanks! Now i got it. – Varun Dalal Sep 08 '20 at 19:54

2 Answers2

2

You should put the script tag at the end of the file otherwise it is executed before the body is parsed

Here is a complete explanation Where should I put <script> tags in HTML markup?

ldekester
  • 121
  • 1
  • 6
  • 1
    Specifically, the script should go, not at the end of the file, but just before `

    `. It would be invalid to have it outside of the `body` or `head` elements.

    – Heretic Monkey Sep 08 '20 at 19:52
1

Well, simply because it is loaded before your HTML, thus the DOM is empty yet.

Defer make it loads after your HTML, it is like if you write your script tag at the bottom of the file (except that defer handles asynchronous stuff when you load many JavaScript files, so it is quicker in a way)

Adrien Kaczmarek
  • 530
  • 4
  • 13