Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference bewteen script before body end and Document onload

What is the difference between placing a script at the end of tag vs adding it on the head and using document on load to assure the html content is already rendered. Placing it at the end of the body wouldnt already assure the content is loaded and ready to manipulate?

like image 811
FRANCISCO BERNAD Avatar asked Jan 30 '26 20:01

FRANCISCO BERNAD


2 Answers

Using the 'onload' event provided by the browser has always worked for me. It has the upside that moving the script tag doesn't break your code.

like image 105
Tobias2222 Avatar answered Feb 02 '26 09:02

Tobias2222


The load event only fires when all images and potentially other resources like style sheets have loaded. This is not yet guaranteed when the script, that is placed at the end of the document body, gets executed. Often that is also not needed for the script to execute correctly, as it can access the DOM.

See also on MDN:

  • load event
  • DOMContentLoaded event
like image 27
trincot Avatar answered Feb 02 '26 09:02

trincot