paint-brush
Insert JavaScript into HTML Using the Script Tagby@manik
16,808 reads
16,808 reads

Insert JavaScript into HTML Using the Script Tag

by ManikApril 10th, 2021
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

The script tag has six attributes that are often underutilized and misunderstood by most JavaScript developers. We will look at all the ways to use the script tag and the importance and use of each of the six attributes. Inline JavaScript is the easiest way to insert JavaScript into an HTML page but not the optimal way of doing it. The type attribute indicates the content type, also known as the MIME type, of the scripting language used in the external file you include in your HTML. This is how you would include a type attribute in your script tag.

Company Mentioned

Mention Thumbnail
featured image - Insert JavaScript into HTML Using the Script Tag
Manik HackerNoon profile picture

The script tag is the primary method to insert JavaScript into the HTML page. The script tag has six attributes that are often underutilized and misunderstood by most JavaScript developers. We will look at all the ways to use the script tag and the importance and use of each of the attributes. If you are an experienced JavaScript developer and just interested in knowing about the script tag's attributes, please feel free to jump to the relevant section.

Using the Script Tag in HTML

The script tag is the primary method to insert JavaScript into HTML. The script tag was created by Netscape and was first implemented in Netscape Navigator 2, as far as the history of JavaScript is concerned. There are two ways you can use the script tag to insert JavaScript in HTML.

Inline JavaScript

You can insert JavaScript directly into an HTML file. Here is an example of how you would do that using the script tag.

<script>
    function helloWorld() {
        console.log('Hello World');
    };
    helloWord();
</script> 

I will go ahead and start with the script tag. Between the script tag, I will create a 

helloWorld
 function that prints the text “Hello World” to the console. On the next line, I will go ahead and invoke the function. This is the simplest way to include JavaScript in your HTML page but not the optimal way of doing it. This approach is good for short scripts or scripts which are page-specific. One more thing you need to remember about inline JavaScript is that it cannot be loaded asynchronously or deferred. Inline JavaScript is hence render-blocking; this means that the browser will parse and execute inline JavaScript from top to bottom before moving to the next line of code. Hence, it’s always better to include the inline JavaScripts (if any) in the page's footer once your HTML and CSS have loaded.

External JavaScript File

Another way to insert JavaScript into your HTML files is by using an external file. This is the most commonly used method to insert JavaScript files into HTML. Let’s have a look at an example. Assuming this is how files are organized in my project, where I have the index.html file and the main.js file, all in the same project folder.

./
├── main.js
├── index.html

This is how we can insert the main.js file into the index.html file. First, I will declare the script tag, and then in the script tag, we will include an attribute called 

src
. The src attribute points to the JavaScript file that we want to include. It’s as simple as that; the main.js file is now included in our HTML.

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

Script Tag Attributes

There is often much confusion between the attributes of the script tag. The confusion is especially centered around two attributes, 

defer
 and 
async
. But let’s look at all the script tag attributes one by one and understand how they impact how the browser treats the external JavaScript file.

type (optional)

The type attribute indicates the content type, also known as the MIME type, of the scripting language used in the external file you include in your HTML. This is how you would include a type attribute in your script tag.

<script src = "main.js" type = "text/javascript" ></script>

<script src = "main.js" type = "application/javascript" ></script>

<script src = "main.js" type = "application/ecmascript" ></script>

Traditionally, the default type has always been 

"text/javascript"
although this has been deprecated now but is still used by many developers. the current default is 
"application/javascript"
 or
"application/ecmascript"
. The safest option is to use these default options; else, using a different MIME type that is not supported by the browser ends up in the script being completely ignored by the browser.

crossorigin (optional)

Web pages often make requests to load resources on other servers. Here is where Cross-Origin Resource Sharing, often abbreviated as CORS, comes in. A cross-origin request is requested for a resource (e.g., style sheets, iframes, images, fonts, or scripts) from another domain. CORS is used to manage cross-origin requests. It defines a way of how a browser and server can interact to determine whether it is safe to allow the cross-origin request. CORS allows servers to specify who can access the assets on the server, among many other things. Here is an example of how you can use the crossorigin attribute.

<script src = "main.js" crossorigin = "anonymous" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" ></script>

<script src = "main.js" crossorigin = "use-credentials" ></script>

So there are two possible options for the crossorigin attribute. The first one being the "anonymous" option. In this case, a cross-origin request is performed, and no credentials are sent. This is often used with the integrity attribute, which sends a hash, and the receiving server verifies the request. We will look into this in detail as the next attribute.

The next possible value for the crossorigin attribute is "use-credentials". In this case, a cross-origin request is performed, and credentials can be sent along with the request. The credentials can be a cookie, a certificate, an HTTP Basic authentication, etc. Most of the time, you would be using the "anonymous" option, but it’s always good to know that an option to send the credentials exists as well.

integrity (optional)

The integrity attribute allows a browser to check the fetched script to ensure that the code is never loaded if the source has been manipulated. I’ll pull an example of the Bootstrap CDN code we often use to insert into our HTML.

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

If you look at this code closely, it uses a 

crossorigin
 of 
"anonymous"
and then there is this integrity attribute, which has something known as the SRI hash, where SRI stands for Subresource Integrity. Subresource Integrity (SRI) is a W3C specification that allows web developers to ensure that resources hosted on third-party servers have not been altered. So this means that the Bootstrap JavaScript being served on your page is as it was uploaded by the Bootstrap team and has not been altered. Use of SRI is highly recommended whenever you are using CORS.

async (optional)

To use the async attribute, all you need to do is include the attribute in the script tag. Please note that the async attribute works only for external JavaScript files and not for inline JavaScript.

<script src = "main.js" async></script>

The async attribute indicates to the browser that the script should start downloading immediately and should not block the rest of the page's rendering. The JavaScript, however, is executed asynchronously with the rest of the page. The async method does not wait for the rest of the DOM to complete loading before it is executed. This is a non-render blocking way of loading your JavaScript.

defer (optional)

Using the defer attribute is as simple as using the async attribute. All you need to do is include the defer attribute in your script tag.

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

When using the defer attribute, the script execution is deferred until after all the document contents have been loaded completely. However, the script starts downloading immediately but is not executed until all the contents have been loaded and are ready.

What Happens If You Neither Include async Nor defer

In case you neither include the async or the defer attribute in your script, your script becomes render-blocking. This means the browser will first parse and execute the script before it moves to the next lines of code in your HTML. This impacts the loading speed of your web page.

Thanks for reading, and hopefully, this was helpful!

I have created an extensive JavaScript cheatsheet. It has been in a manner where it becomes easy for you to refer to each property and method for various JavaScript objects. It’s absolutely free to download from the above link ☺.

Previously published at https://cloudaffle.com/post/insert-javascript-in-html