Load Javascript Last


Im 99% sure that a few weeks ago I saw an easy way to make your javascript load after the rest of the page has loaded… however I didnt bookmark the page.

If anyone knows how to do this then please let me know :slight_smile:

If you put your javascript inside window.onload, then it will fire only after the entire page has loaded. E.g.:

window.onload = function() {
  document.getElementsByTagName('p').style.background = 'red';

That will give all p elements a red background after the page has loaded.

I should have been clearer but my knowledge of JS is very poor, however my HTML is

<script language='javascript' src='URL'></script>

(javascript include I think its called?)

So the option to use onload isnt there. I thought there was something I could put after the language=‘javascript’ part… but I really cant remember.

<script type="text/javascript">
window.onload = function() {
  document.getElementsByTagName('p').style.background = 'red';

Don’t use language=“javascript” (note the double quotes, not single quotes), use type=“text/javascript” instead. And if you put that in the <head> of your document, it does what I said before. It’s the same as doing

<body onload="document.getElementsByTagName('p').style.background = 'red';">

but putting it in the head in a separate file is much neater. Have a look at this.

<script src=“script.js” type=“text/javascript” defer=“defer”></script>

the defer attribute tells browsers that they can delay downloading the actual Javascript file until after the rest of the page has loaded as there is nothing in there that needs to run prior to the onload event being triggered. Not all browsers actually delay the download though as it is a suggestion rather than a requirement.

DEFER!! That was it!! thanks very very much :slight_smile:

Nice…I feel that my site loads faster.