rozerro rozerro - 2 months ago 24
Javascript Question

Loading jquery in the last position

I offen heard that loading jquery as last element is a good idea because this way a web page loads faster. At the same time I have a script in the header which shows error:

$(document).ready(function () {// Uncaught ReferenceError: $ is not defined
...
}


Should I move jquery loader before the script or I need to change this script some way?

Answer

Your concrete issue stems from the fact that you execute statements that use jQuery (i.e. they execute $, which is a function in the jQuery library, also called "the jQuery function" because jQuery is an alias) before it is loaded.

True, it is typically recommended to load scripts last, but that still means the scripts have to be loaded in the correct order, with usually jQuery before your own scripts using jQuery.

If you really want to load your own scripts before jQuery for some reason, you need to defer its execution and have a third helper script to run it, e.g.:

// script.js
(function() {
  function myLibraryMainFn() {
    $('div').text('simulating work, utilizing jQuery');
  }

  window.myNamespace = {
    run: function() {
      myLibraryMainFn()
    }
  };
}());
<!DOCTYPE html>
<html>
  <body>
    <div></div>
    <script src="script.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script>
      // Run your script now:
      window.myNamespace.run();
    </script>
  </body>
</html>