- In-depth Look Into The JavaScript Script Tag Attributes
- Inline JavaScript
- External JavaScript File
- Script Tag Attributes
- type (optional)
- crossorigin (optional)
- integrity (optional)
- async (optional)
- defer (optional)
- What Happens If You Neither Include async Nor defer
- JavaScript Where To
- Example
- JavaScript Functions and Events
- Example
- Demo JavaScript in Head
- Example
- Demo JavaScript in Body
- External JavaScript
- External file: myScript.js
- Example
- External JavaScript Advantages
- Example
- External References
- Example
- Example
- Example
- HTML Tag
- Syntax
- Important notes
- Example of HTML tag:
- Differences Between HTML 4.01 and HTML5
- Differences Between HTML and XHTML
- Attributes
In-depth Look Into The JavaScript Script Tag Attributes
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.
function helloWorld() console.log('Hello World'); >; helloWord();
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.
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 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.
src = "main.js" type = "text/javascript" > src = "main.js" type = "application/javascript" > src = "main.js" type = "application/ecmascript" >
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.
src = "main.js" crossorigin = "anonymous" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" > src = "main.js" crossorigin = "use-credentials" >
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.
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous">
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.
The async attribute indicates 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.
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. Get Access To More Such Stories on Cloudaffle
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 ☺.
JavaScript Where To
In HTML, JavaScript code is inserted between tags.
Example
Old JavaScript examples may use a type attribute: .
The type attribute is not required. JavaScript is the default scripting language in HTML.
JavaScript Functions and Events
A JavaScript function is a block of JavaScript code, that can be executed when «called» for.
For example, a function can be called when an event occurs, like when the user clicks a button.
You will learn much more about functions and events in later chapters.
JavaScript in or
You can place any number of scripts in an HTML document.
Scripts can be placed in the , or in the section of an HTML page, or in both.
JavaScript in
In this example, a JavaScript function is placed in the section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
Demo JavaScript in Head
JavaScript in
In this example, a JavaScript function is placed in the section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
Demo JavaScript in Body
Placing scripts at the bottom of the element improves the display speed, because script interpretation slows down the display.
External JavaScript
Scripts can also be placed in external files:
External file: myScript.js
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a tag:
Example
You can place an external script reference in or as you like.
The script will behave as if it was located exactly where the tag is located.
External scripts cannot contain tags.
External JavaScript Advantages
Placing scripts in external files has some advantages:
- It separates HTML and code
- It makes HTML and JavaScript easier to read and maintain
- Cached JavaScript files can speed up page loads
To add several script files to one page — use several script tags:
Example
External References
An external script can be referenced in 3 different ways:
- With a full URL (a full web address)
- With a file path (like /js/)
- Without any path
This example uses a full URL to link to myScript.js:
Example
This example uses a file path to link to myScript.js:
Example
This example uses no path to link to myScript.js:
Example
You can read more about file paths in the chapter HTML File Paths.
HTML Tag
The HTML tag declares client-side script (JavaScript) in an HTML document. When defining a client-side script the script tag is used for image manipulation, form validation, and dynamic changes of content. The tag can include either the script itself or a link to an external file containing scripts.The path to the external file is specified with src attribute.
Syntax
The ) tags.
Important notes
There are a few ways an external script can be executed:
- The async="async" attribute indicates, that the scripts are executed asynchronously, simultaneously with the loading of the page.
- When there is no async and defer="defer" , the script is executed after the loading of the page.
- If there is no async and defer, the script is executed before the loading of the page.
For selecting an HTML element, JavaScript uses the document.getElementById() method.
Example of HTML tag:
html> html> head> title>Title of the document title> head> body> p id="example"> p> script> document.getElementById("example").innerHTML = "My first JavaScript code"; script> body> html>
Differences Between HTML 4.01 and HTML5
HTML 4 requires the type attribute, whereas it is optional in HTML5. In HTML5, the async attribute is a new one. HTML5 does not support the HTML 4.01 xml:space attribute.
Differences Between HTML and XHTML
In XHTML, the content inside scripts is declared as #PCDATA (instead of CDATA). In such cases, the entities will be parsed.
In XHTML, all special characters must be encoded, or all the content must be wrapped inside a CDATA section.
Attributes
Attribute | Value | Description |
---|---|---|
async | async | Defines that the script is executed asynchronously. (For external scripts only). Not supported in IE9 and older versions. |
charset | charset | Defines character encoding, used in an external file with the JavaScript code. |
defer | defer | Defines, that the script must be executed after the loading of the page. (For external scripts only). |
src | URL | Defines the URL of an external file with the JavaScript code. (Can be defined either relative, or an absolute URL). |
type | media_type | Defines the MIME-type of the script. |