Script running when placed in body tag but not in head tag on vscode

Hi there, I am facing a weird problem with my codes. While trying to learn responsive web design using JS, I wrote this code on vs code running live server.

https://codepen.io/croy4744/pen/YzGmNGE

On live server, everything works fine when I placed the script link in body tag but when I copy the same script src link in head tag, it doesn’t run. What could be the possible reason for this?

Because when the script is in head, it tries to interact with HTML elements before they’re created.

1 Like

Thanks for your repsonse. It makes sense now.

But then is it that the scripts in head tag can’t interact with HTML elements once they are created?

there are ways to defer when the script is loaded, try make a search for that

1 Like