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.
- Is there a better way to handle this.
- 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.