Using document.ready vs window.load to load deferred content

1.4k views Asked by At

I know the difference between document.ready and window.load events. Now in order to improve the performance of my website, I plan to defer loading of javascript. I've seen numerous examples of lazy-loading content:

  1. Inject <script src="..."> and <link rel="stylesheet" href="..."> on document.ready
  2. Inject <script src="..."> and <link rel="stylesheet" href="..."> on window.load
  3. Inject <script src="..."> and <link rel="stylesheet" href="..."> few seconds after document.ready is fired
  4. Inject <script src="..."> and <link rel="stylesheet" href="..."> few seconds after window.load is fired

My first question is which of these methods is preferable.

My second question is that that I want to know what exactly happens when I use approach #1. If my document has this content defined in HTML source:

<!-- head -->
<link>
<script>
<!-- body -->

and in document.ready I inject these additional tags:

<!-- head -->
<link>
<script>
<link class="lazyload">
<script class="lazyload">
<!-- body -->
<img><img><img><img><img>

I am wondering what exactly will the browser do:

  1. When exactly will it fire the document.ready event
  2. In what order will it download the files
  3. Will it block the page while attempting to download the injected files
2

There are 2 answers

1
pmaruszczyk On BEST ANSWER

This may be helpfull: Loading Scripts Without Blocking, but it answer only few questions.

0
Niet the Dark Absol On

The way I do things is to load scripts wherever, mostly in the <head>, then keep a queue-like array of functions to be run, then just before the </body> I iterate through those scripts and run them. I could put all the scripts at the end of the <body> if I chose to, but I find it easier to put the <script> tags next to where they are relevant - much easier for finding them again.

If this is not to your liking, you can set the async and defer attributes of the <script> tag. This means download and execution of the scripts will wait until resources are available (such as bandwidth from the page finishing its download).

If you require images and other content to be loaded before a particular code is run, use window.load. Otherwise, document.ready is fine.