Search code examples
javascriptlazy-loadingdocument-readywindow-load

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


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

Solution

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