-4

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?

rozerro
  • 5,787
  • 9
  • 46
  • 94

2 Answers2

1

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>
Community
  • 1
  • 1
Jeroen
  • 60,696
  • 40
  • 206
  • 339
-1

Always refer library file first(in your case jQuery), then use it next..For page load and performance add it before body end tags of your HTML

Satz
  • 105
  • 9