[SalesForce] Issue with “jQuery(document).ready” in lightning

I am facing some weird issue with javascript in lightning. Below is the piece of code in my javascript file:

jQuery(document).ready(function() {
    lw.sampleFunction();
});

var lw = {};

lw.sampleFunction = function() {
    console.log('Sample Function Call');
}

When I am loading my page, it's throwing script exception :

Uncaught TypeError: Cannot read property 'sampleFunction' of undefined

It seems like sampleFunction is being called before is definition. If I change the order of document.ready and put in below function definition, it starts working.

It seems like lightning is not able to identify the ready state and document.ready is always true for it.

Has anyone faced similar issue? Is there any solution for this problem?

Thanks,

Best Answer

Lightning starts loading components well after the DOMContentLoaded phase, so any methods that you call (jQuery or otherwise) that depend on this state will execute immediately instead of being placed in the asynchronous event queue. Lightning itself starts running after DOMContentLoaded itself, in fact, because it has to wait until it is fully loaded before it can run. Whatever you're trying to do, you'll want to place your code in the afterScriptsLoaded handler of ltng:require.

Related Topic