Should I wait for DOMContentLoaded
event if I place a script
tag with the corresponding JS file at the end of a body
tag?
index.html
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="popup.css">
</head>
<body>
<div id="container"></div>
<script src="popup.js"></script>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', onDOMContentLoaded);
DOMContentLoaded does not wait for stylesheets to load, however deferred scripts do wait for stylesheets, and DOMContentLoaded queues behind deferred scripts. Also, scripts which aren't deferred or async (e.g. <script> ) will wait for already-parsed stylesheets to load.
The script tag should always be used before the body close or at the bottom in HTML file. The Page will load with HTML and CSS and later JavaScript will load.
Using the script tag to include an external JavaScript file The script tag should either be included between the <head> tags or just before the closing <body> tag in your HTML document. JavaScript is often placed before the closing body tag to help reduce the page loading time.
The DOMContentLoaded event is a useful event that can make a big impact on the performance of your pages, hence this example. It fires when the HTML and scripts that make up the page have loaded, but not necessarily the images or CSS.
Basically no. If script modifies element, it needs to exist.
If you put script after that element it exists.
If you put it Before, it does not exist and you may want to use DOMContentLoaded to wait for script to execute until it's sure it exists.
<div id="myid"></div>
<script>
getElementById('myid'); // it will work, Element myid Is defined
<script>
But this
<script>
getElementById('myid'); // it will fail, it's not yet defined, it will be
// Using DomContentLoaded here would be requrired
<script>
<div id="myid"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With