Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - $(document).ready() executing BEFORE element load

So, I'm loading some data from a MVC3 action that returns Json, containing some parameters and content as a string. I append the content to some div. In the partial view I have a document.ready JQuery event. For some reason that function executes before the content is appended and all the selectors I declare in the ready function are empty.

Is there a logic reason for this? Is I set a timeout the selectors see the elements. But a timeout can be very imprecise.

Any suggestions?

Thanks!

Example code fiddle: http://jsfiddle.net/aKxy7/

like image 901
Luis Aguilar Avatar asked Apr 05 '11 03:04

Luis Aguilar


People also ask

Why do we start our code with document ready () in jQuery?

ready() function will load as soon as the DOM is loaded and before the page contents are loaded. You should wrap all your javascript code with this function to ensure that the code only runs when the page is fully rendered.

Which jQuery function can you use to execute when the document finished loading?

ready( handler )Returns: jQuery. Description: Specify a function to execute when the DOM is fully loaded.

Which jQuery function is used to prevent code from running before the document is finished loading?

The Document Ready Event This is to prevent any jQuery code from running before the document is finished loading (is ready). It is good practice to wait for the document to be fully loaded and ready before working with it.

What does $( document .ready function () mean?

$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.


1 Answers

It sounds like you are expecting $(document).ready() to fire after all assests are loaded. That's not how $(document).ready() works. It is triggered when the DOM is finished rendering. Nothing more. It sounds like you want to use $(window).load(), which does wait until all assets are loaded.

like image 100
Alex Avatar answered Oct 23 '22 22:10

Alex