sukesh
sukesh

Reputation: 2437

DOM loading slow with code to wait for jQuery

I'm working on a Sitecore project where the Javascript libraries are referenced inside components and they would load before jQuery.

[Consider it as JS library referenced inside .cshtml (MVC)]

This means the JS file loads before jQuery and this would throw an error in console - $ is undefined

[Currently, jQuery is placed at the end of body tag, the usual place.]

To handle this, the custom JS files have this approach to wait for jQuery:

var readyForFileA = (callbackForFileA) => {
    if (document.readyState != "loading") {
        callbackForFileA();
    }
    else {
        document.addEventListener("DOMContentLoaded", callbackForFileA);
    }
}

readyForFileA(() => {
   $(txt).click(function(){
       some_method();
   });
});

function some_method(){
}

Now the problem is, there are many such files with similar "wait until jQuery loads" code which is slowing down DOM loading for the pages, as I guess it is going in a loop until DOM loads.

  1. Is there a better way to handle this.
  2. The simplest way is to move jQuery reference to head, but there are 40 such files where the code has to be updated to $(document).ready()
    So, can just this part be modified.

var readyForFileA = (callbackForFileA) => {
        if (document.readyState != "loading") {
            callbackForFileA();
        }
        else {
            document.addEventListener("DOMContentLoaded", callbackForFileA);
        }
    }

Something like var readyForFileA = $(document).ready();

So, that the next part need not change

readyForFileA(() => {
   ....
});

If not please suggest a better alternative.

Upvotes: 0

Views: 485

Answers (1)

Shyne
Shyne

Reputation: 339

Defer Scripts

You can try using the defer attribute on the scripts, that way they are fetched after the page content finished loading, which will help with page loading performance:

<head>
    <script defer src="./myscript.js"></script>
</head>

Window Events

The window object has lots of events you can use for this. After a quick google search it doesn't seems like jQuery has some event to wait for, that's why i'm going to use the window.load event instead:

// Wait for the page to load
window.addEventListener("load", () => {
   // Code to execute once the page has loaded
   $(txt).click(() => {
       some_method();
   });
});

Note that you might want want to use other window events if your code needs to be ran as soon as possible.

Also note that callbacks are considered bad practice, use promises instead.

Upvotes: 1

Related Questions