如果未加载jQuery,则加载它

3
我已经创建了一个以下格式的jQuery插件。在某些网站上,我发现会收到如下错误信息:TypeError: $.myApp不是一个函数
我也注意到一些网站可能会多次包含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);


可能是重复的问题:如果jQuery尚未加载,如何加载它? - bain
2个回答

4
您可以使用Ben Alman的书签生成器(Bookmarklet generator代码源)中的代码。
(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 */

  }
);

我仍然得到相同的错误。我该如何确保在调用插件的地方也加载了jQuery? - Asa Carter
请确保您将代码添加到上面代码中标有 /* YOUR JQUERY CODE GOES HERE */ 的位置。 - Mottie

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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接