Load scripts last

So you’ve got your HTML and CSS sorted and you’ve started to drop in some customs scripts to make things a bit interactive. To keep things in shape it pays to develop some good habits early on.

One such habit is placing your scripts just before the closing body tag like this:

...

<script type="text/javascript">
  var secretWords = prompt( "What are the secret words?" );
  var welcomeMessage = document.querySelector( "h1" );
  function unlockBatCave( secretWords ) {
    if ( secretWords === “Ironman sucks” ) {
      welcomeMessage.textContent = “He sure does, right this way sir”;
    } else {
      welcomeMessage.textContent = “Nice try Joker”;
    }
  }
</script>

</body>

</html>

We do this because it allows the full HTML page load before the script runs. This means the page contents will appear faster for the user and the HTML will be ready for you to manipulate it with the script.

The second thing you should do is split your scripts out into a separate file rather than writing them directly into your HTML files. Loads of online tutorials use inline scripting because it’s easy for demonstration purposes, but it isn’t good practice in reality.

Once you’ve moved your code into a separate file update your script tag like this:

<script type="text/javascript" src="your-javascript-file.js"></script>


Posted

by

in