rozerro rozerro - 1 year ago 100
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 Source

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() {
<!DOCTYPE html>
    <script src="script.js"></script>
    <script src=""></script>
      // Run your script now:;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download