jQuery Plugin: Limiting script tag references to other libraries
I am about to create a jQuery plugin but I was thinking of using a few other libraries. Now for it to be easy to use I was wondering if there are ways to limited the amount of script tag references I have to add.
Few options I was considering:
1: Include the library code i开发者_运维知识库nto the plugin code. Not sure if this is viable? It will increase the size of the plugin.
2: I just read about google.loader so I don't know a lot about it yet. Seems like a way you can load libraries from inside your code using Google API. It does require an API key though so this might not be for everybody.
So StackOverflow, how do you deal with this problem?
I wouldn't include other libraries from inside the plugin, nobody wants to use a plugin that has hidden includes to external libraries that could possibly break the main program.
If you are looking for a way to include scripts without manually adding script tags, you can try the jQuery.loadScript or any equivalent methods from closure/google or YUI.
Here is another simple method I used once that works pretty well:
function loadScript( url, callback ) {
var done = false,
script = document.createElement('script');
script.src = url;
script.async = true;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState ||
this.readyState == 'loaded' || this.readyState == 'complete') ) {
done = true;
if (typeof callback == 'function') {
callback.call( window, script );
}
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
}
};
var s = document.getElementsByTagName( 'script' )[0];
s.parentNode.insertBefore( script, s );
};
精彩评论