0

I have a <head> full of .css, .js and metadata. But there is just one script that will not run properly if it is put in the <head> of the html. It will only work if it is at the end of the file.

What I would like to know is, if there are any documentation regarding this or a special type of rules I should follow as a beginner web designer.

<html>
<head>
 <link href="css/style.css" rel="stylesheet">
 <link href="css/style2.css" rel="stylesheet">
 <script src="js/script.js"></script>
 <script src="js/scipt2.js"></script>
</head>
<body>
<----------HTML---------->
</body>
 <script src="js/secret.js"></script>
</html>
newcool
  • 319
  • 2
  • 20
  • putting your code at the end of the document just ensures that the dom has loaded before the script. i havent' put a script in the head of a document in about 10 years. there are very, very few instances when a script really needs to be in the head. – I wrestled a bear once. Jun 13 '19 at 19:04

1 Answers1

6

The modern way to solve this issue is to use the defer attribute on the script tag. Put all your tags in the <head>

From MDN:

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

So this:

<script src="js/secret.js"></script>

becomes this:

<script defer src="js/secret.js"></script>

But the tag now goes into the <head>.

Randy Casburn
  • 13,840
  • 1
  • 16
  • 31