如何在第三方网站上正确加载jQuery插件?

时间:2015-04-10 23:28:27

标签: javascript jquery jquery-plugins widget

我正在构建一个使用一些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之外,我仍然会收到原始的TypeError错误。

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

0 个答案:

没有答案