Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

3 Ways to Include Javascript in HTML

INTRODUCTION
MORE THAN MEETS THE EYE

Welcome to a tutorial on how to include Javascript in HTML. So you have just started with Javascript and wondering how to properly “implement” Javascript into an HTML file? The quick and dirty answer to that is – Just use a pair of HTML Script tags.

But there are a couple more things to take note of – Where should Javascript be placed? The head or body section? Does the order matter? This guide will walk through all these mysteries, and read on to find out!

I have included a zip file with all the example code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!

NAVIGATION
TABLE OF CONTENTS

Section A
Ways to Include JS

Section B
Loading Order

Extras
Download & More

Closing
What Next?

SECTION A
WAYS TO INCLUDE JAVASCRIPT IN HTML

Before we dive deeper into the mysteries, let us start by answering the basics of “how to use Javascript in HTML” with a few simple examples.

1) CODE IT WITHIN A PAIR SCRIPT TAGS

example-1.html


  
    

This is an HTML page.

As with the introduction above, the simplest way is to use a pair of tags in HTML, and just sandwich the Javascript in between.

EXTRA) SCRIPT IN THE HEAD OR BODY?

The next million dollar question is – Shall we put the  tags in the  or  section of the HTML? Well,  tags can actually be put into both sections. But please take note that there is a stark difference where you put them and the order of the scripts do matter – We will go through this in more details below.

EXTRA) A BLAST FROM THE PAST

If you have poked around the various tutorials all over the Internet, you might have spotted a few  tags with the type or language attribute. That is actually something from the past, where we have to define the type of script being used. But with today’s standards, we can safely omit it and browsers will automatically assume it is Javascript by default.

2) INCLUDE AN EXTERNAL JAVASCRIPT FILE

example-2.html


  
    

This is an HTML page.

example-2.js
var sad = "Goodbye";
var bloke = "World";
alert(sad + " " + bloke);

As scripts can become long, stinky, and complicated – It only makes sense to put them into a  separate file. In this case, we use the same pair of tags in HTML, but define a source src attribute to point to the external Javascript file.

We do not need any “special” software or gimmicks to create JS files – They are just plain text files like HTML.

EXTRA) RELATIVE & ABSOLUTE SCRIPT URL


If we do not define the domain in the src attribute, the browser will automatically assume a relative path with the current URL. For example, if we are visiting a page at https://my-site.com/about/, that src="my-script.js" will resolve to https://my-ninja-site.com/about/my-script.js.

So please do be very careful with the relative and absolute URL. This is actually a common pitfall among beginners, where they wonder “why is my script not working!?”… When the path is wrong, and the script is not even loaded in the first place.

EXTRA) MINIFICATION

/* THE HUMAN READABLE FORM */
function sayHello(){ 
  var crikey = "Hello"; 
  var mate = "World"; 
  alert (crikey + " " + mate);
}
 
/* MINIFIED */
function sayHello(){var crikey="Hello";var mate="World";alert(crikey+" "+mate)}

Want to speed up the loading of your websites? Then minify all your external Javascript – Minification is but a simple process where we strip all the line breaks and unnecessary white spaces (computers don’t need these to work) to reduce the file size and speed up the overall loading time.

No, we do not need any special tools again. There are plenty of free minify tools available online, such as the minifier. Just remember to keep a copy of the “human readable version” for yourself.

3) CODE IT INLINE

example-3.html


  
  
    

This is an HTML page.

Lastly, we can directly code Javascript into the elements itself, usually to handle certain events and user actions, for example:

  • onclick – When the user clicks on the element.
  • onhover – As the mouse cursor hovers over the element.
  • onkeypress – When the user presses a key.

THE CHEATSHEET

Ways to Include Javascript in HTML (click to enlarge)

SECTION B
LOADING ORDER OF SCRIPTS

Remember from earlier when we learned script tags can be placed into both the head and body sections? That the order of the scripts do matter? Well yes, let us go into that in more details in this section.

SCRIPTS ARE LOADED FROM TOP TO BOTTOM

Some of you guys may be thinking that the scripts are loaded “all at once”, without any particular order – But no. Here is an example of how it actually works:

example-4.html



  

Contents

example-4-first.js
alert("This script will load first");
example-4-second.js
alert("This script will load next");
  • The scripts will be loaded in the order of “from top to bottom”.
  • Scripts that you define closer to the top of the HTML page will be loaded first (this is inclusive of CSS files as well), scripts at the bottom of the page will be loaded last.
  • Meaning, in the example above, the file example-4-first.js will be loaded first, then followed by example-4-second.js.

WHY IS THE LOADING ORDER IMPORTANT?

While the loading order of the script may seem insignificant at first, but there are 2 main reasons why it is so important:

BLOCKING SCRIPTS

If we place a huge Javascript file right at the top, we will have wait for it to finish loading before the rest of the page can proceed. This is what we call a “blocking” Javascript, where the loading of the entire page is slowed down by just one obese script. This is also why some developers prefer to put the non-essential Javascript right at the very bottom of the page instead.

CASE OF THE MISSING VARIABLES

Now, consider the following scripts:

example-5-first.js
var message = "Hello World!";
example-5-second.js
alert(message);
example-5.html




  
  

If we load them in the order of first-second, then nothing will go wrong as the message variable will be defined first. But once we reverse the loading order of the scripts, it will throw an error because alert cannot find the message variable.

DEFER THE LOADING OR LOAD IT ASYNCHRONOUSLY

Now that you know why the loading order is so important, here is a little bit of extra – We can defer the loading of a Javascript so that it does not block the loading; Deferred scripts will only load after the HTML is done.

ample-6d.html



  

HTML page

But use this with care, or you might mess up the loading order and end up with a few unintentional missing variables plus library functions. Alternatively, we can set the script to be loaded asynchronously:

ample-6e.html



  

HTML page

This way, the script will be loaded in parallel with other scripts. But please take note again –

  • The browser will determine the best loading pattern, it may not always follow the async directive.
  • It is not the best way to “speed up” the page loading.
  • This can still potentially mess up the loading order. It is still wise to load the library and frameworks first, and your own scripts last.

EXTRA
DOWNLOAD & MORE

That’s it for the examples, and here is the download link for all the examples, plus a few extras that you may be useful to you.

THE SUMMARY

  • There are 3 ways to include Javascript into HTML:
    • Sandwich the Javascript in between a pair of  tags.
    • Point to an external Javascript file using the  tag and src attribute.
    • Code it inline into the elements. Usually to handle events and user actions, for example, onclickonhover, and onkeypress.
  • It is all right to put  tags in both the  and  sections, but the order of the scripts do matter.
  • If you do not define the full URL within the src of a  tag, the browser will automatically assume a relative path with the current URL.
  • Computers do not need line breaks and comments, we can safely strip these in our Javascript and make things load faster – This process is called minification.
  • Scripts are loaded in the order of “from top to bottom”.
  • We can use the defer attribute to push the loading of the script to the last.
  • We can also use the async attribute to make the script load asynchronously with the rest.

EXAMPLE CODE DOWNLOAD

Click here to download the example code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

CLOSING
WHAT NEXT?

Thank you for reading, and we have come to the end of this short tutorial. I hope it has helped you understand Javascript a little better, and if there is anything you want to add to this guide, please feel free to comment below. Good luck and happy coding!

 Javascript IntroductionJS Variables & Data-Types


The post 3 Ways to Include Javascript in HTML appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

3 Ways to Include Javascript in HTML

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×