$(document).ready() fires too early $(document).ready() fires too early jquery jquery

$(document).ready() fires too early


If you rely on external content to be already loaded (e.g. images, fonts), you need to use the window.load event

$(window).on("load", function() {    // code here});

The behaviour of these events is described in this article:

There is [a] ready-state however known as DOM-ready. This is when the browser has actually constructed the page but still may need to grab a few images or flash files.

Edit: changed syntax to also work with jQuery 3.0, as noted by Alex H


Quote OP:

"As I understood, the $(document).ready() function was fired when the document is completed,"

$(document).ready() fires when the DOM ("document object model") is fully loaded and ready to be manipulated. The DOM is not the same as the "document".

W3C - DOM Frequently Asked Questions

You can try $(window).load() function instead...

$(window).load(function() {    // your code});

It will wait for all the page's assets (like images and fonts, etc.) to fully load before firing.


The jQuery .ready() function fires as soon as the DOM is complete. That doesn't mean that all assets (like images, CSS etc) have been loaded at that moment and hence the size of elements are subject to change.

Use $(window).load() if you need the size of an element.