Question: is there anything wrong with using the following method to defer running code until after jQuery has loaded (or until another fixed point)?
Bonus question: is there a better way to do it? (E.g. not having to name the functions in window.deferred, like window.deferred.afunction)
In my page (before jQuery):
<script>
window.deferred = window.deferred || {};
window.deferred.afunction = function() {
console.log('afunction is running');
};
window.deferred.anotherfunction = function() {
console.log('anotherfunction is running');
};
</script>
In my JS (after jQuery when I'm ready to execute my deferred functions):
/* Run deferred functions */
if(window.deferred && typeof window.deferred === 'object') {
for (var fn in window.deferred) {
if (typeof window.deferred[fn] == 'function') {
window.deferred[fn]();
}
}
}
Demo: https://jsfiddle.net/j4sqy5kf/4/
As far as I can tell it works fine. But I consider myself amateur at JavaScript - I can write it but don't always understand how it's working.
So far all the ways I've found to do this (e.g. http://snipplr.com/view/54863/) rely on having setTimeout or setInterval and calling a check function, which seems quite inelegant to me.
There's also Require.js, which I believe could be used, but I think it's overkill to achieve exactly what I want as it primarily serves a different purpose.
Background
I'm writing a post for my blog in Markdown, and I'm writing a little JavaScript inside the page to manage some hidden content. I want to use jQuery in my script, but jQuery is loaded in the footer - so, I want an elegant way to defer execution of my inline script until after jQuery has loaded.
I have jQuery in my footer and a general.js script, in which most of the rest of my JavaScript runs. I'd like to run the 'In my page' bits inside each blog post, and leave the 'In my JS' bit in general.js so I never have to worry about it again.
I know I could define but not execute the functions, but I don't want to have to update general.js each time (e.g. add function1(), function2(), etc.)
I want it to automatically loop through all deferred functions.