Uncaught TypeError: undefined не является функцией - typeahead.js

Я пытаюсь получить базовый typeahead.js пример для работы. Этот пример работает, если я создаю его в отдельном файле HTML, как показано ниже.

<html>
<head>
<script type="text/javascript" src="/static/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/static/js/typeahead.bundle.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        var substringMatcher = function(strs) {
          return function findMatches(q, cb) {
            var matches, substringRegex;

            // an array that will be populated with substring matches
            matches = [];

            // regex used to determine if a string contains the substring `q`
            substrRegex = new RegExp(q, 'i');

            // iterate through the pool of strings and for any string that
            // contains the substring `q`, add it to the `matches` array
            $.each(strs, function(i, str) {
              if (substrRegex.test(str)) {
                // the typeahead jQuery plugin expects suggestions to a
                // JavaScript object, refer to typeahead docs for more info
                matches.push({ value: str });
              }
            });

            cb(matches);
          };
        };

        var djs = ['Hardwell', 'Armin van Buuren', 'Avicii', 'Tiesto', 'David Guetta', 
                   'Dimitri Vegas & Like Mike', 'Nicky Romero', 'Steve Aoki', 'Afrojack', 
                   'Dash Berlin', 'Skrillex', 'Deadmau5', 'Alesso', 'W&W', 'Calvin Harris', 
                   'NERVO', 'Above & Beyond', 'Sebastian Ingrosso', 'Axwell', 'Aly & Fila', 
                   'Markus Schulz', 'Daft Punk', 'Headhunterz', 'Zedd', 'Knife Party', 
                   'Swedish House Mafia', 'Showtek', 'Andrew Rayel', 'Fedde Le Grand', 
                   'Dyro', 'Laidback Luke', 'Paul van Dyk', 'ATB', 'Angerfist', 'Dada Life',
                   'Kaskade', 'Frontliner', 'Steve Angello', 'Sander Van Doorn', 
                   'Martin Garrix', 'Porter Robinson', 'Ferry Corsten', 'Chuckie', 
                   'Krewella', 'Coone', 'Carl Cox', 'Bobina', 'Omnia', 'Orjan Nilsen', 
                   'Zatox', 'Gareth Emery', 'Bingo Players', 'Infected Mushroom', 
                   'Eric Prydz', 'Tommy Trash', 'Wildstylez', 'Arty', 'R3hab', 'Madeon', 
                   'Vicetone', 'Brennan Heart', 'DJ Feel', 'Gunz For Hire', 'Diplo', 
                   'Tenishia', 'Noisecontrollers', 'Mike Candys', 'DJ Antoine', 
                   'Quentin Mosimann', 'Project 46', 'Blasterjaxx', 'D-Block & S-te-Fan', 
                   'Dillon Francis', 'Dannic', 'Adaro', 'Richie Hawtin', 'Martin Solveig', 
                   'Felguk', 'Myon & Shane 54', 'Cosmic Gate', 'Heatbeat', "John O'Callaghan", 
                   'Wasted Penguinz', 'Tiddey', 'Skazi', 'Da Tweekaz', 'Tenashar', 
                   'Bob Sinclar', 'Benny Benassi', 'Stafford Brothers', 'DJ BL3ND', 
                   'Paul Oakenfold', 'Mat Zo', 'Diego Miranda', 'DJs From Mars', 'Matt Darey',
                   'UMEK', 'Solarstone', 'Ummet Ozcan', 'Ran-D', 'Disclosure', 'Rudimental',
                   'Flux Pavilion', 'Nero', 'Datsik', 'Moby', 'Zeds Dead', 'The Prodigy',
                   'Bassnectar', 'Adventure Club', 'Dirty South', 'Borgore', 'Modestep', 
                   'Bonobo', 'Feed Me', 'Flosstradamus', 'The Glitch Mob', 'Rusko',
                   'Kill The Noise','Fatboy Slim', 'Zomboy', 'A-Trak', 'James Blake', 
                   'Morgan Page', 'The Bloody Beetroots', 'Quintino', 'Wolfgang Gartner', 
                   'Bakermat', 'M83', 'Pretty Lights', 'Cedric Gervais', 
                   'Sunnery James & Ryan Marciano', 'Baauer', 'Danny Avila', 'Justice', 
                   'Seven Lions', 'Royksopp', 'Bondax', 'Zero 7', 'Lemaitre', 'Noisia', 
                   'Gramatik', 'Thomas Gold', 'Basement Jaxx', 'Aphex Twin', 'Four Tet', 
                   'Flying Lotus', 'Sidney Samson', 'Paul Kalkbrenner', 'Boards Of Canada', 
                   'Maya Jane Coles', 'Groove Armada', 'Juan Magan', 'Chase & Status', 'BT', 
                   'Digitalism', 'Mount Kimbie', 'Benga', 'Audien', 'Bassjackers', 
                   'The Chainsmokers', 'DVBBS', 'Pete Tong', 'Deorro', 'DJ Snake', 
                   'Don Diablo', 'Pendulum', 'Chris Lake', 'Dzeko & Torres', 'Zhu'
        ];

        $('#dj-search .typeahead').typeahead({
          hint: true,
          highlight: true,
          minLength: 1
        },
        {
          name: 'djs',
          displayKey: 'value',
          source: substringMatcher(djs)
        });
    }); 
</script>
</head>

<body>
<form id="search_bar" class="navbar-form navbar-left">
    <div class="form-group" id="dj-search">
        <input type="text" class="form-control typeahead" placeholder="Search favourite DJs" autocomplete="off">
    </div>
</form>
</body>
</html>

Если я попытаюсь заставить тот же код работать для моего существующего шаблона HTML, я продолжаю получать ошибку

Uncaught TypeError: undefined is not a function

на линии

$('#dj-search .typeahead').typeahead({

Что может вызвать эту ошибку?

Ниже мой полный HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>EDM Hunters | Top 100 DJs | Discover the Best of Electronic Dance Music</title>

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Listen to, vote on and discover the Top Electronic Dance Music Songs by the Top DJs of the world">
        <meta property="og:image" content="/static/img/edmlogo.jpg"/>

        <link rel="shortcut icon" href="/static/img/favicon.ico">
        <link href="/static/css/bootstrap.min.css" rel="stylesheet" type='text/css'/>
        <link href="/static/css/bootstrap-theme.min.css" rel="stylesheet" type='text/css'/>
        <link href="/static/css/style.css" rel="stylesheet" type='text/css'/>

        <script type="text/javascript" src="/static/js/jquery-1.9.1.js"></script>
        <script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="/static/js/typeahead.bundle.min.js"></script>
        <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-53a4066858ab24f0"></script>

        <script type="text/javascript">
            $(document).ready(function() {
                var substringMatcher = function(strs) {
                  return function findMatches(q, cb) {
                    var matches, substringRegex;

                    // an array that will be populated with substring matches
                    matches = [];

                    // regex used to determine if a string contains the substring `q`
                    substrRegex = new RegExp(q, 'i');

                    // iterate through the pool of strings and for any string that
                    // contains the substring `q`, add it to the `matches` array
                    $.each(strs, function(i, str) {
                      if (substrRegex.test(str)) {
                        // the typeahead jQuery plugin expects suggestions to a
                        // JavaScript object, refer to typeahead docs for more info
                        matches.push({ value: str });
                      }
                    });

                    cb(matches);
                  };
                };

                var djs = ['Hardwell', 'Armin van Buuren', 'Avicii', 'Tiesto', 'David Guetta', 
                           'Dimitri Vegas & Like Mike', 'Nicky Romero', 'Steve Aoki', 'Afrojack', 
                           'Dash Berlin', 'Skrillex', 'Deadmau5', 'Alesso', 'W&W', 'Calvin Harris', 
                           'NERVO', 'Above & Beyond', 'Sebastian Ingrosso', 'Axwell', 'Aly & Fila', 
                           'Markus Schulz', 'Daft Punk', 'Headhunterz', 'Zedd', 'Knife Party', 
                           'Swedish House Mafia', 'Showtek', 'Andrew Rayel', 'Fedde Le Grand', 
                           'Dyro', 'Laidback Luke', 'Paul van Dyk', 'ATB', 'Angerfist', 'Dada Life',
                           'Kaskade', 'Frontliner', 'Steve Angello', 'Sander Van Doorn', 
                           'Martin Garrix', 'Porter Robinson', 'Ferry Corsten', 'Chuckie', 
                           'Krewella', 'Coone', 'Carl Cox', 'Bobina', 'Omnia', 'Orjan Nilsen', 
                           'Zatox', 'Gareth Emery', 'Bingo Players', 'Infected Mushroom', 
                           'Eric Prydz', 'Tommy Trash', 'Wildstylez', 'Arty', 'R3hab', 'Madeon', 
                           'Vicetone', 'Brennan Heart', 'DJ Feel', 'Gunz For Hire', 'Diplo', 
                           'Tenishia', 'Noisecontrollers', 'Mike Candys', 'DJ Antoine', 
                           'Quentin Mosimann', 'Project 46', 'Blasterjaxx', 'D-Block & S-te-Fan', 
                           'Dillon Francis', 'Dannic', 'Adaro', 'Richie Hawtin', 'Martin Solveig', 
                           'Felguk', 'Myon & Shane 54', 'Cosmic Gate', 'Heatbeat', "John O'Callaghan", 
                           'Wasted Penguinz', 'Tiddey', 'Skazi', 'Da Tweekaz', 'Tenashar', 
                           'Bob Sinclar', 'Benny Benassi', 'Stafford Brothers', 'DJ BL3ND', 
                           'Paul Oakenfold', 'Mat Zo', 'Diego Miranda', 'DJs From Mars', 'Matt Darey',
                           'UMEK', 'Solarstone', 'Ummet Ozcan', 'Ran-D', 'Disclosure', 'Rudimental',
                           'Flux Pavilion', 'Nero', 'Datsik', 'Moby', 'Zeds Dead', 'The Prodigy',
                           'Bassnectar', 'Adventure Club', 'Dirty South', 'Borgore', 'Modestep', 
                           'Bonobo', 'Feed Me', 'Flosstradamus', 'The Glitch Mob', 'Rusko',
                           'Kill The Noise','Fatboy Slim', 'Zomboy', 'A-Trak', 'James Blake', 
                           'Morgan Page', 'The Bloody Beetroots', 'Quintino', 'Wolfgang Gartner', 
                           'Bakermat', 'M83', 'Pretty Lights', 'Cedric Gervais', 
                           'Sunnery James & Ryan Marciano', 'Baauer', 'Danny Avila', 'Justice', 
                           'Seven Lions', 'Royksopp', 'Bondax', 'Zero 7', 'Lemaitre', 'Noisia', 
                           'Gramatik', 'Thomas Gold', 'Basement Jaxx', 'Aphex Twin', 'Four Tet', 
                           'Flying Lotus', 'Sidney Samson', 'Paul Kalkbrenner', 'Boards Of Canada', 
                           'Maya Jane Coles', 'Groove Armada', 'Juan Magan', 'Chase & Status', 'BT', 
                           'Digitalism', 'Mount Kimbie', 'Benga', 'Audien', 'Bassjackers', 
                           'The Chainsmokers', 'DVBBS', 'Pete Tong', 'Deorro', 'DJ Snake', 
                           'Don Diablo', 'Pendulum', 'Chris Lake', 'Dzeko & Torres', 'Zhu'
                ];

                $('#dj-search .typeahead').typeahead({
                  hint: true,
                  highlight: true,
                  minLength: 1
                },
                {
                  name: 'djs',
                  displayKey: 'value',
                  source: substringMatcher(djs)
                });
            }); 
        </script>
    </head>
    <body>
        <div id="edmhunters_body">
            <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
                <div class="container">
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                            <span class="sr-only">Toggle navigation</span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                        <a class="navbar-brand" href="#"><img id="edm" src="/static/img/edmlogo.png" alt="EDM Hunters logo"/></a>
                    </div>
                    <div class="collapse navbar-collapse">
                        <ul class="nav navbar-nav">
                            <li class="active">
                                <a href="#"><strong>Top 100 DJs</strong></a>
                            </li>
                            <li>
                                <a href="/explore/"><strong>Explore More DJs</strong></a>
                            </li>
                            <li>
                                <a href="/genres/"><strong>Browse by Genres</strong></a>
                            </li>
                            <li>
                                <a href="/monthly/"><strong>Monthly Top Songs</strong></a>
                            </li>
                            <li>
                                <a href="/trending/"><strong>Trending Songs</strong></a>
                            </li>
                        </ul>
                        <form id="search_bar" class="navbar-form navbar-left">
                            <div class="form-group" id="dj-search">
                                <input type="text" class="form-control typeahead" placeholder="Search favourite DJs" autocomplete="off">
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="container">
                <div class="jumbotron" style="color:white;background-color:#252525;">
                    <h1>EDM Hunters</h1>
                    <p>EDM Hunters is a place where you can listen to and discover the Top Electronic Dance Music Songs by the Top DJs of the world. Don't agree with a list? Vote for your favourite song. What your #1?</p>
                    <p><a class="btn btn-primary btn-lg" role="button" href="/faq/">Learn more</a></p>
                </div>
                <div class="col-md-11">
    <div class="row dj_row">
        <div class="col-md-2 col-md-offset-1 text-center dj-md-2">
            <p><strong>#1 Hardwell</strong></p>
            <a href="/hardwell/"><img src="/static/img/1.jpg" class="img-rounded dj_img" alt="Hardwell"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#2 Armin van Buuren</strong></p>
            <a href="/armin-van-buuren/"><img src="/static/img/2.jpg" class="img-rounded dj_img" alt="Armin van Buuren"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#3 Avicii</strong></p>
            <a href="/avicii/"><img src="/static/img/3.jpg" class="img-rounded dj_img" alt="Avicii"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#4 Tiesto</strong></p>
            <a href="/tiesto/"><img src="/static/img/4.jpg" class="img-rounded dj_img" alt="Tiesto"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#5 David Guetta</strong></p>
            <a href="/david-guetta/"><img src="/static/img/5.jpg" class="img-rounded dj_img" alt="David Guetta"/></a>
        </div>
    </div>
    <div class="row dj_row">
        <div class="col-md-2 col-md-offset-1 text-center dj-md-2">
            <p><strong>#6 Dimitri Vegas &amp; Like Mike</strong></p>
            <a href="/dimitri-vegas-and-like-mike/"><img src="/static/img/6.jpg" class="img-rounded dj_img" alt="Dimitri Vegas &amp; Like Mike"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#7 Nicky Romero</strong></p>
            <a href="/nicky-romero/"><img src="/static/img/7.jpg" class="img-rounded dj_img" alt="Nicky Romero"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#8 Steve Aoki</strong></p>
            <a href="/steve-aoki/"><img src="/static/img/8.jpg" class="img-rounded dj_img" alt="Steve Aoki"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#9 Afrojack</strong></p>
            <a href="/afrojack/"><img src="/static/img/9.jpg" class="img-rounded dj_img" alt="Afrojack"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#10 Dash Berlin</strong></p>
            <a href="/dash-berlin/"><img src="/static/img/10.jpg" class="img-rounded dj_img" alt="Dash Berlin"/></a>
        </div>
    </div>
    <div class="endless_container">
        <a class="endless_more" href="/?page=2"
            rel="page">more</a>
        <div class="endless_loading" style="display: none;"><img src="/static/img/ajax-loader.gif" style="margin-left:535px;margin-top:25px;" alt="loading"/></div>
    </div>
                    <script src="/static/js/jquery-1.9.1.js"></script>
                    <script src="/static/js/endless-pagination.js"></script>
                    <script>
                        $.endlessPaginate({
                            paginateOnScroll: true,
                            paginateOnScrollMargin: 130
                        });
                    </script> 
                </div>
            </div>
            <div class="push"></div>
        </div>
        <div class="footer">
            <div id="disclaimer">
                <p>*Rankings according to <a href="#" onclick="location.href='http://www.djmag.com/top100?year=2013'; return false;" target="_blank">DJ Mag Top 100 DJs 2013</a></p>
            </div>  
            <footer>
                <span id=copy class='pull-right'><strong>&copy; EDM Hunters 2014</strong></span>
                <a href="/contact/" id="contactus" class='pull-right'>Contact us</a>
                <a href="/faq/" id="faq" class="pull-right">FAQ</a>
                <div class="clearfix"></div>
            </footer>   
        </div>
        <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-53a4066858ab24f0"></script>
        <script>
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
            ga('create', 'UA-47063606-1', 'edmhunters.com');
            ga('send', 'pageview');
        </script>
    </body>
</html>

Ответ 1

Как обсуждалось в комментариях: эта проблема была решена оригинальным плакатом. "undefined не является функцией" означает, что свойство typeahead было фактически undefined - поэтому он не может быть запущен как вызов функции. Обычно это указывает на проблему с загрузкой плагина, но:

  • Плагин typeahead был загружен после jQuery и
  • На консоли не было ошибок, предполагая, что плагин не загружается.

В итоге на странице была загружена другая копия jQuery. Таким образом, jQuery загружался в head, затем загружался плагин typeahead (создавая $('foo').typeahead())... и затем загружалась вторая копия, уничтожая расширенную функцию jQuery. Когда вызов document.ready был запущен, этот второй jQuery стал использоваться, в результате чего возникла ошибка.