javascript - widget用法 - widget是什么



如何正确加载第三方网站上的jQuery插件? (0)

我正在构建一个使用几个jQuery插件的小部件。

它通过以下方式部署:

<script src="http://example.com/widget"></script>
<div id="widget"></div>

抓取的脚本如下所示:

(function() {
  var jQuery;
  // Look for jQuery on page; if there, use it, otherwise fetch it
  if (window.jQuery === undefined || window.jQuery.fn.jquery !== '2.1.3') {
    loadScript("//code.jquery.com/jquery-2.1.3.min.js", scriptLoadHandler);
  } else {
    jQuery = window.jQuery;
    loadExternalLibraries();
    main();
  }

  // Fetch 3rd party libraries from server
  function loadExternalLibraries() {
    <% widget_javascripts.each do |filename| %>
      var url = "//example.com/widget/javascripts/" + "<%= filename %>";
      loadScript(url, function() {
        console.log("Added " + "<%= filename%>");
      });
    <% end %>
  }

  function loadScript(url, callback) {
    /* Load script from url and calls callback once it's loaded */
    var scriptTag = document.createElement('script');
    scriptTag.setAttribute("type", "text/javascript");
    scriptTag.setAttribute("src", url);
    if (typeof callback !== "undefined") {
      if (scriptTag.readyState) {
        /* For old versions of IE */
        scriptTag.onreadystatechange = function () { 
          if (this.readyState === 'complete' || this.readyState === 'loaded') {
            callback();
          }
        };
      } else {
        scriptTag.onload = callback;
      }
    }
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(scriptTag);
  }

  function scriptLoadHandler() {
    jQuery = window.jQuery.noConflict(true);
    loadExternalLibraries();      
    main();
  }

  function main() {
    jQuery(document).ready(function($) {
      $('#widget').plugin1();
    });
  }
})();

jQuery似乎加载正常,但$('#widget').plugin1()返回经典TypeError: $(...).plugin1 is not a function

所以我试着在这个帖子后面( http://alexmarandon.com/articles/widget-jquery-plugins/ )把这个插件包装到另外一个函数中,然后像这样传递了本地的jQuery变量:

// Plugin1 code
function initPlugin1(jQuery) {
  (function ($) {
    # plugin code here
  }(jQuery));
}

// modified loadExternalLibraries function
function loadExternalLibraries() {
  % widget_javascripts.each do |filename| %>
    var url = "//example.com/widget/javascripts/" + "<%= filename %>";
    loadScript(url, function() {
      initPlugin1(jQuery);
    });
  <% end %>
}

除了提醒说initPlugin1 is not defined为每个其他的插件库initPlugin1 is not defined ,我还是得到了原始的TypeError错误。

假设我有4-5个这样的插件可以获取(没有一个可能被缩小),我是否正确地处理这个问题?





widget