Mechanism for resource loading awareness in DOM ready

Description

Script loaders that load scripts asynchronously and on demand may have scripts still loading with DOMContentLoaded/DOM ready fires. Ideally, jQuery would not fire its DOM ready actions until all scripts are loaded.

This is complicated by the fact that jQuery could be loaded after the page has loaded, so it needs to be able to know via some property besides document.readyState to know if all the scripts are ready.

Attached is a test file for a possible approach to this, where a new property is added to document.documentReady, "resourceLoading", to indicate if something is still being loaded. I have no preference on the name of the property, this is just a placeholder suggestion, to indicate the desired behavior.

John Resig thought that such a mechanism should be based on a counter, to allow something more than just a binary value if different types or numbers of resources need to indicate a loading dependency, so that approach is used for the value of the property.

It uses a dynamically created event to indicate changes to the value. By using an event, jQuery can listen to changes in the value, to know when it goes to zero, so its DOM ready callbacks can occur.

Hopefully something like this approach would allow any type of script loader to communicate that something is occurring that should prevent ready callbacks from being fired, without having to make more specific changes to jQuery.

By using an inspectable, global generic property that is tied to an event system to get updates on the value, it should provide robust communication of state.

Ideally a global property could be avoided, but I do not see another way to let jQuery know the state of script loading as soon as possible. If jQuery is loaded after the page loads, it checks as part of loading for document.readyState, and if the script that loads jQuery also has other scripts bundled with it that register DOM ready callbacks, those callbacks would be triggered before a script loader could call a jQuery specific function to indicate scripts are loading.

Hopefully this approach could then also be used by other JS libraries that provide DOM ready functionality but still want to participate in dynamic, async script loading.

Change History (6)

Isn't this too monolithic, or did I miss something about the implementation? Ideally you'd want to pair the "ready" code for a particular script file with the loading of that script alone, so that the page could be (at least minimally) functional before everything loads.