Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a jQuery function only after the document finish loading

Strange situation:

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

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

and...

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

For some reason, even BEFORE all the document finish loading, I'm getting the alert message with an incorrect width. Only when I release the message, the rest of the document loads and I'm getting the right width as it should be.

Why my function is being called BEFORE all the document finish loading? Is there a way to load the function only AFTER a certain element done loading (Example: the nav element)?

like image 650
Lior Elrom Avatar asked Apr 19 '13 18:04

Lior Elrom


People also ask

How do we make a function available after the document is loaded?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

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 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.

How can we call a method after page load in jQuery?

after page loading? Method 2: Using the ready() method: The ready() method in jQuery is used to execute code whenever the DOM becomes safe to be manipulated. It accepts a handler that can be passed with the function required to be executed. It will now invoke the function after the page has completed loading.


2 Answers

You can use window.load, it will be triggered after all the resource have completed loading.

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

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading, Reference

like image 138
Adil Avatar answered Nov 12 '22 16:11

Adil


All the current solutions are just treating symptoms of the main problem. If you want your handler to execute after all your ajax loads, then you may use a promise.

var ajax1 = $.ajax();
var ajax2 = $.ajax();

jQuery(function($) {
    $.when.apply($, [ajax1, ajax2]).done(function() {
        // your code here
    });
});
like image 36
Brad M Avatar answered Nov 12 '22 17:11

Brad M