HTML script async
Created By: chatGPT
In HTML, you can load scripts asynchronously to improve the performance of your webpages. This allows the browser to continue parsing and rendering the page while the script is being downloaded. To do this, you can use the
async
attribute in your <script>
tag. Here’s how it works:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Async Script Example</title>
</head>
<body>
<h1>Welcome to Asynchronous JavaScript!</h1>
<script src="script.js" async></script>
</body>
</html>
The
async
attribute tells the browser to download the script file in the background, and once it is downloaded, the script will execute immediately, without waiting for other resources to finish loading. This helps keep your webpage responsive, especially if you have large scripts or multiple scripts to load.// script.js
console.log('Script loaded asynchronously!');
Keep in mind that when using
async
, the order of script execution is not guaranteed. If your scripts depend on each other, consider using the defer
attribute instead, which maintains the order of execution but still allows for non-blocking loading.<script src="script1.js" defer></script>
<script src="script2.js" defer></script>
Here's an example of how to use the
defer
attribute while combining it with async
for scripts that load independently:<script src="async-script.js" async></script>
<script src="defer-script.js" defer></script>