Lior Elrom Lior Elrom - 4 months ago 10
Javascript Question

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)?

Answer

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

Comments