Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 804
Salman A Avatar asked Mar 26 '26 11:03

Salman A


1 Answers

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.

like image 104
Niet the Dark Absol Avatar answered Mar 29 '26 01:03

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!