I have built a chrome extension which one of the functions is to check for jQuery on the page and if it does not exist then to add it to the page. I repurposed some code from an older extension and whilst it works as expected (99% of the time) I want to understand the usage of setTimeout in this context.
Both setTimeout(addjQuery)
and addjQuery()
seem to work just fine in most cases. Here is the code as it stands and like I said it does work almost always.
Updated to ask a specific question... I am injecting both jquery and myLibrary into the page using the syntax below. As you can see in the onMyLibraryLoaded function that I am trying to use jQuery to attach a blur event to all inputs. This works almost always... Is there a reason why it would sometimes throw an error that jQuery is not defined. My only explanation is that occasionally the myLibrary loads faster than jquery and fires before jquery was ready? Is that right? How would I go about fixing this? await?
if (!window['jQuery']) {
setTimeout(addjQuery);
}
if (!window['myLibrary']) {
setTimeout(addMyLibrary);
}
function addjQuery() {
const script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js';
script.onload = onjQueryLoaded;
document.body.appendChild(script);
}
function addMyLibrary() {
const script = document.createElement('script');
script.src = 'https://jrags/myLibrary.min.js';
script.onload = onMyLibraryLoaded;
document.body.appendChild(script);
}
function onMyLibraryLoaded(){
$(document).on("blur", "#someInput", function(){
console.log("Input blurred");
})
}
function onjQueryLoaded(){
console.log('jquery loaded sucessfully')
}