Javascript jQuery Scripts

Trying to distribute the resources loaded on a page through a function that loads the JavaScript as dynamic files and not all at once, I ran into a problem: None of the following function calls was useful for dynamic scripts:

  • .on (“load”, handler)
  • .on (“ready”, handler)
  • $ (document) .ready (handler)
  • $ (window) .load (handler)
  • window.onload = handler
  • document.addEventListener (“DOMContentLoaded”, handler)

I searched all over the internet, and found all sorts of similar problems:

  • jQuery document.ready() not firing for dynamically loaded content ?
  • Why isn’t DOM ready working for my scripts?
  • How to bind dynamic content to document-ready events?
  • Script not loading when added dynamically with jQuery ?

but nowhere could I find an answer and I could barely find a satisfactory solution to my problem !

Now to clarify the problem and expose the solution, here is the original code:

$(window).on('load',function(){ 
	codeToRun();
});

And here is actually what I changed:

if (document.readyState === 'complete') {
	codeToRun();
} else {
	$(window).on('load',function(){
		codeToRun();
	});
}

This solution actually solves two problems: it retains compatibility with the variant when the code is loaded normal or with defer attribute, but also when it is loaded dynamically or using async.

So, this is the simple and practical solution if you want to run javascript code immediately after loading a javascript file, even if the html page has been fully loaded and ready long before!

Tags: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *