【问题标题】:Load jQuery if not loaded如果未加载,则加载 jQuery
【发布时间】:2020-11-17 16:47:59
【问题描述】:

我创建了一个格式如下的 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);

【问题讨论】:

标签: javascript jquery


【解决方案1】:

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

  }
);

【讨论】:

  • 我仍然遇到同样的错误。如何确保在调用插件的地方也加载了 jQuery?
  • 确保将代码添加到上面代码中/* YOUR JQUERY CODE GOES HERE */ 的位置。
【解决方案2】:

根据 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 2012-09-19
    • 2017-12-03
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多