In HTML, there are several ways to include a JavaScript file. I'll explain four different methods, their drawbacks, and finally, highlight the best approach.
1. in
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="custom.js"></script> </head> <body> </body> </html>
In this approach while parsing code javascript file loaded first before html inside body and If the JavaScript tries to manipulate elements in the body that haven’t been parsed yet, it can lead to errors, as the HTML content hasn’t fully loaded.
This blocking behavior delays the parsing and rendering of the rest of the page, affecting performance and user experience.
2. in
(at the end)<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script src="custom.js"></script> </body> </html>
In this approach, the HTML is fully parsed before the JavaScript is loaded and executed, preventing errors related to missing DOM elements. This approach is all good but since HTML parsing and JavaScript loading happen sequentially, it can take longer duration overall, as the two processes occur at different times
3. in
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="custom.js" async></script> </head> <body> </body> </html>
In this approach, we make the JavaScript asynchronous, so it doesn’t block the HTML from loading. Both HTML parsing and JavaScript loading happen in parallel. However, if the JavaScript executes before the HTML is fully parsed and js tries to manipulate html elements that haven’t loaded yet, it can cause errors.
Note: — this approach can save the time but by loading html ,js simultaneously but more vulnerable to error
4. in
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="custom.js" defer></script> </head> <body> </body> </html>
This approach is similar to the third one, where both HTML parsing and JavaScript loading happen in parallel. However, even if the JavaScript loads first, the browser waits until the HTML is fully parsed before executing the script
The best way is usually to use:
Why:
In cases where the script is independent of DOM content (like tracking scripts or ads), you can use async for better performance.
The above is the detailed content of Best Way to add Javascript file in HTML. For more information, please follow other related articles on the PHP Chinese website!