Firing scripts on page load
by
, 02-11-2018 at 09:15 PM (62442 Views)
EDIT 02-12: I added some ameliorations to the tutorial and designated a 'best method' for firing load events.
Many people think that putting a script at the end of the body section guarantees that it will fire because of its position in the document. While this is true in many cases, we can't rely on this because a script put at the end of the document starts to run as soon as the dom is ready (unless we inform it to wait using a timeout or another method). At this 'domready stage', there may be elements on our page that are still loading, which could prevent our script from working properly. So putting a script at the end of the body section does not guarantee that it will always fire.
window.onload=... and <body onload="..."> do guarantee this, but using these onloads has its restrictions. For instance, simply adding a window.onload=... to a page already containing this line will override the script that is already there: only the last window.onload=... will execute. There are ways to circumvent this problem, but it would be nicer if we could add lines for firing load events to already existing ones without further ado. This topic is the subject of this tutorial.