1. Defer Attribute
2. Async Attribute
3. Dynamic Loading
var script = document.createElement(‘script’);
script.src = ‘example.js’;
1. Use the async attribute: The async attribute tells the browser to load the script asynchronously, which means that it will not block the rendering of the page. This can significantly improve the loading speed of your website. However, it is important to note that async scripts may not execute in the order in which they are specified in the HTML code.
2. Use the defer attribute: The defer attribute also allows the script to load asynchronously, but it ensures that the scripts are executed in the order in which they are specified in the HTML code. This is useful when the order of script execution is important for the functionality of the website.
3. Place scripts at the bottom of the page: Placing scripts at the bottom of the page allows the HTML content to load first, which can improve the perceived loading speed of the website. This also ensures that the scripts do not block the rendering of the page.
Step-by-Step Guide: Linking External JS File in HTML
Step 1: Create a New File
The first step is to create a new file in your preferred text editor. You can use any text editor, such as Notepad, Sublime Text, or Visual Studio Code. Save the file with a .js extension, for example, “myscript.js”.
Step 3: Save Your File
Once you’ve written your JS code, save the file and make sure it’s in the same directory as your HTML file.
Now it’s time to link your JS file in HTML. To do this, you’ll need to add a script tag in the head section of your HTML file, like this:
<head> <script src="myscript.js"></script> </head>
The “src” attribute specifies the location of your JS file. In this case, it’s in the same directory as your HTML file, so you only need to provide the file name.
Step 5: Test Your Code
Save your HTML file and open it in a web browser. You should see the “Hello World” alert message appear. Congratulations, you’ve successfully linked your external JS file in HTML!
<script> tag in the appropriate location and use the
async attributes when necessary to optimize the loading process. With these techniques, you can ensure that your website runs smoothly and efficiently for all users. Happy coding!