加载jQuery如果没有加载

时间:2015-11-30 00:10:33

标签: javascript jquery

我在下面的格式中创建了一个jQuery插件。在某些网站上,我发现我收到了TypeError: $.myApp is not a function等错误消息。

我还注意到其中一些网站可能不止一次包含jQuery,其他插件可能包含jQuery版本,或者jQuery甚至可能根本不加载。我对这些网站没有任何控制权或正在使用其他插件。

无论安装了哪些其他插件和版本的jQuery,如何确保我的插件可靠运行?



;(function($, window, document, undefined) {
	var myApp = function(options) {

		this.init = function() {
		};
		
		this.init();
	};
	
	$.myApp = function(options) {
		return myApp (options);
	};
})(jQuery, window, document);




2 个答案:

答案 0 :(得分:4)

您可以使用Ben Alman Bookmarklet generatorcode 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 */

  }
);

答案 1 :(得分:0)

基于Mottie的回答(请首先提出请求),如果您希望将jQuery注入现有页面 - 例如,通过DevTools控制台,请逐行输入:

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;