动态加载jQuery,然后再加载Typeahead.js

Dynamically load jQuery and then Typeahead.js

本文关键字:加载 Typeahead js jQuery 动态 然后      更新时间:2023-09-26

我正在尝试动态加载jQuery,然后动态加载Typeahead.js jQuery插件。

我可以加载jQuery,但typeahead插件似乎无法加载。代码的第一部分检查jQuery,如果它不存在,则动态加载它。

加载jQuery后,我将尝试使用$.getScript加载Typeahead,该脚本在jQuery文档中用于加载jQuery插件。然而,Typehead插件似乎无法加载,因为当我尝试调用Bloodhound(Typeahead中的建议引擎)时会出现错误。

我通过将下面显示的typeahead代码放入Rails应用程序来确认它是有效的。当与jquery rails gem和资产管道一起使用时,typeahead代码会用JSON响应正确地填充我的输入框。然而,我不能依赖Rails,当我试图分离代码时,我无法按正确的顺序动态加载库。

如有任何帮助,我们将不胜感激。

(function() {
    // Localize jQuery variable
    var jQuery;
    /******** Load jQuery if not present *********/
    if (window.jQuery === undefined) {
      var script_tag = document.createElement('script');
      script_tag.setAttribute("type","text/javascript");
      script_tag.setAttribute("src",
        "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js");
        if (script_tag.readyState) {
          script_tag.onreadystatechange = function () { // For old versions of IE
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
              scriptLoadHandler();
            }
          };
        } else { // Other browsers
          script_tag.onload = scriptLoadHandler;
        }
        // Try to find the head, otherwise default to the documentElement
        var parentHead = (document.getElementsByTagName("head")[0] || document.documentElement)
        parentHead.insertBefore(script_tag, parentHead.firstChild);
    } else {
      // The jQuery version on the window is the one we want to use
      jQuery = window.jQuery;
      main();
    }
    /******** Called once jQuery has loaded ******/
    function scriptLoadHandler() {
      // Restore $ and window.jQuery to their previous values and store the
      // new jQuery in our local jQuery variable
      jQuery = window.jQuery.noConflict(true);
      // Load Typeahead
      // Call our main function
      main();
    }
    /******** Our main function ********/
    function main() {
      jQuery(document).ready(function($) {
     /******* This is the call to load typeahead *******/
        var url = "https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"
        $.getScript(url, function(){
          var companies = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            limit: 3000,
            prefetch: {
              // url points to a json file that contains an array of country names, see
              // https://github.com/twitter/typeahead.js/blob/gh-pages/data/countries.json
              url: '/accounts.json',
            }
          });
          // kicks off the loading/processing of `local` and `prefetch`
          companies.initialize();
          // passing in `null` for the `options` arguments will result in the default
          // options being used
          $('#the-basics .search .typeahead').typeahead(null, {
            name: 'companies',
            displayKey: 'name',
            // `ttAdapter` wraps the suggestion engine in an adapter that
            // is compatible with the typeahead jQuery plugin
            source: companies.ttAdapter()
          });
        });
      });
    }
  })();

我以前尝试过编写依赖加载程序,它非常复杂,尤其是在跨浏览器方面。去年,我遇到了一个与您类似的问题,我需要以非常特定的顺序加载jQuery(可能)和一堆其他库。我可以让它在Chrome中工作,但不能在IE等中工作。每次我做出改变时,时间问题似乎都会悄悄出现!

在尝试了许多与您相同的代码行后,我放弃了,最终发现:http://headjs.com/

从那以后,我一直只使用HeadJs,我的代码只有几行(与我之前构建的巨大怪物相反)

不确定使用库是否适用,但如果适用,我强烈推荐使用此库。

顺便说一句,注意有一个"head.ready"活动将取代你通常的Dom-ready。当您的库都很好地加载并准备就绪时,此事件就会启动!提示:您需要使用head.ready来启动所有javascript操作!