Home > loader > how to load js file in html

how to load js file in html

Release time:2023-06-28 21:12:43 Page View:1000 author:Yuxuan
How to Load JS File in HTMLAs websites become increasingly dynamic, JavaScript files have become more and more essential in creating sophisticated and responsive websites. In this article, we will explore how to load JS files in HTML, and the different methods available to achieve this.Method 1: Inline ScriptThe simplest method is to include the JS code directly into the HTML file using an inline script. The script can be added in the head or body section of the document using the script tag. Here’s an example:

Inline Script

This is the easiest way to add a script to your HTML document. Simply include the script in the head or body section of the document using the script tag.

```html

Click the button to change the text:

```This method is quick and easy, but it's not recommended for larger scripts as it can slow down the loading of the web page.Method 2: External ScriptA better approach is to add the JavaScript code externally through an external script file. This is usually achieved using the script tag, specifying the source of the script file with the \"src\" attribute. Here’s an example:

External Script

By using an external script, we can keep the HTML and JS code separate. This makes it easier to maintain the code and make changes to the code individually.

```html

Click the button:

```In this case, the JS code is stored in an external file called \"script.js\". This is a better method for larger scripts, as it reduces the size of the HTML file, making it quicker to download.Method 3: Async and DeferIn addition to the two methods above, HTML5 introduces two new attributes: \"async\" and \"defer\". These attributes tell the browser how to load the script file.

Async and Defer

These attributes control when the script is loaded and executed. The \"async\" attribute loads the script asynchronously with HTML parsing, while the \"defer\" attribute loads the script after HTML parsing is complete.

Here's an example:```html ```In this case, the \"async\" attribute is used to load the script file asynchronously. This means that the script file will be downloaded in the background while the browser continues to parse the HTML file.```html ```In this case, the \"defer\" attribute is used to load the script file after the HTML file has been parsed. This means that the script file will be downloaded in the background while the browser continues to load and parse the HTML file. ConclusionIn conclusion, there are multiple ways to load JS files in HTML, each with its own benefits. Using an external script file is recommended for larger scripts, while Async and Defer attributes help in controlling when the script is loaded and executed. By choosing the right method of loading JS files, your website can become more responsive and dynamic.
THE END

Not satisfied with the results?