How to load jQuery function only after document loading is completed

Strange situation:

I am building a menu bar using jQuery and CSS .
In my JavaScript file, I have an on-ready function, for example:

 $(document).ready(function(e) { mark_active_menu(); } 

and...

 function mark_active_menu() { var elementWidth = $("nav li").width(); alert(elementWidth); } 

For some reason, even before everything finishes loading the document, I get a message with the wrong width. Only when I release the message, the rest of the document is loaded, and I get the correct width, as it should be.

Why is my function called BEFORE THE ACHIEVEMENT OF ACHIEVEMENT OF DOCUMENT? Is there a way to load a function only after loading a specific element (example: nav element)?

+7
source share
6 answers

You can use window.load , it will start after the resource has finished loading.

 $(window).load(function(e) { mark_active_menu(); }); 

The load event is fired at the end of the document loading process. At this point, all objects in the document are in the DOM, and all the images and subframes have finished loading, Link

+11
source

All current solutions simply treat the symptoms of the underlying problem. If you want your handler to execute after all ajax downloads, you can use the promise.

 var ajax1 = $.ajax(); var ajax2 = $.ajax(); jQuery(function($) { $.when.apply($, [ajax1, ajax2]).done(function() { // your code here }); }); 
+5
source

Try entering a window load event:

 $(window).load(function() { //Stuff here }); 
+3
source

To make sure, try the load window

 $(window).load(function(e) { mark_active_menu(); } 
+2
source

Before (sometimes it does not load absolutely at the beginning, a few milliseconds after (0-200 ms)):

 $(document).ready(function(){ $('body').hide(0); }); 

After:

 $(window).load(function(){ $('body').delay(500).show(0); }); 
0
source

In my situation, working with AJAX and HTML. I have the same problem with the functions $ (document) .ready () and $ (window) .load (). I solved this problem by adding my event handler (which should work in HTML DOC) to the jQuery function, which runs immediately after the AJAX reguest completes. Read this: "jQuery.post ()" (third parameter in the function).

In my code, it looks like this:

 var RequestRootFolderContent = function(){ $.post( 'PHP/IncludeFiles/FolderContent.inc.php', function(data){ $('[class~="folder-content"]').html(data); //Here what you need $('[class~="file"]').dblclick(function(){ alert("Double click"); }); } ) } 
0
source

All Articles