Reputation: 2225
I have created a jQuery plugin in format below. On some sites I've noticed that I get an error message like TypeError: $.myApp is not a function
.
I've also noticed that some of these sites may include jQuery more than once and that other plugins can include versions of jQuery or that jQuery may not even be loaded at all. I don't have any control of these sites or what other plugins are being used.
How can I make sure my plugin runs reliably regardless of what other plugins and versions of jQuery are installed?
;(function($, window, document, undefined) {
var myApp = function(options) {
this.init = function() {
};
this.init();
};
$.myApp = function(options) {
return myApp (options);
};
})(jQuery, window, document);
Upvotes: 3
Views: 2107
Reputation: 40030
Building upon Mottie's answer, if you wish to inject jQuery into an existing page - for example, via the DevTools console, type this in line by line:
var myscript = document.createElement( 'script' );
myscript.type = 'text/javascript';
myscript.src = 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js';
document.documentElement.childNodes[0].appendChild( myscript );
TEST IT:
$('div').length;
Upvotes: 0
Reputation: 86403
You could use the code from Ben Alman's Bookmarklet generator (code source):
(function( window, document, req_version, callback, $, script, done, readystate ){
// If jQuery isn't loaded, or is a lower version than specified, load the
// specified version and call the callback, otherwise just call the callback.
if ( !($ = window.jQuery) || req_version > $.fn.jquery || callback( $ ) ) {
// Create a script element.
script = document.createElement( 'script' );
script.type = 'text/javascript';
// Load the specified jQuery from the Google AJAX API server (minified).
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/' + req_version + '/jquery.min.js';
// When the script is loaded, remove it, execute jQuery.noConflict( true )
// on the newly-loaded jQuery (thus reverting any previous version to its
// original state), and call the callback with the newly-loaded jQuery.
script.onload = script.onreadystatechange = function() {
if ( !done && ( !( readystate = this.readyState )
|| readystate == 'loaded' || readystate == 'complete' ) ) {
callback( ($ = window.jQuery).noConflict(1), done = 1 );
$( script ).remove();
}
};
// Add the script element to either the head or body, it doesn't matter.
document.documentElement.childNodes[0].appendChild( script );
}
})( window, document,
// Minimum jQuery version required. Change this as-needed.
'1.3.2',
// Your jQuery code goes inside this callback. $ refers to the jQuery object,
// and L is a boolean that indicates whether or not an external jQuery file
// was just "L"oaded.
function( $, L ) {
'$:nomunge, L:nomunge'; // Used by YUI compressor.
/* YOUR JQUERY CODE GOES HERE */
}
);
Upvotes: 4