I have a very basic jQuery plugin which I load into my webpage like so:
(function() {
var tk = document.createElement('script');
tk.src = '//www.test.com/scripts/jq_plugin.js';
tk.type = 'text/javascript';
tk.async = 'true';
tk.onload = tk.onreadystatechange = function() {
var rs = this.readyState;
if (rs && rs != 'complete' && rs != 'loaded') return;
};
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(tk, s);
})();
Then, I call the plugin like so:
$(function(){
$('#test').jq_plugin();
});
But when the page loads I am getting this error:
Uncaught TypeError: undefined is not a function
(anonymous function)
I understand why - the plugin is being called before the script is loaded. I know a quick and dirty hack is just to use a setTimeout()
around the plugin call but I don't want to do that. I've tried inserting the script before and after jQuery but get the same result.
How can I do this without a timeout?
This is a stripped down version of the plugin:
(function ( $ ) {
$.fn.jq_plugin = function(options){
return this.each(function() {
return $(this).click(onClick);
function onClick(e){
console.log('ID: '+$(this).attr('id'));
}
});
};
}( jQuery ));