Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I wait for DOMContentLoaded event if I place a script tag at the end of a body tag

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);
like image 364
FrozenHeart Avatar asked Jan 15 '16 09:01

FrozenHeart


People also ask

Does DOMContentLoaded wait for scripts?

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.

Is it better to place the JavaScript code at the beginning or the end of the webpage?

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.

Why is the script tag placed towards the end of the body tag?

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.

When should I use DOMContentLoaded?

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.


1 Answers

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>
like image 61
Grzegorz Avatar answered Nov 16 '22 02:11

Grzegorz