1

I'm loading jquery.min.js in the footer. It works fine as long as there are no inline jquery calls in the body of the document before the script include.

For example,

<div><script>jQuery(document).ready(function(){//jQuery('anything')});</script></div>

Throws an error:

Uncaught ReferenceError: jQuery is not defined (index):63 (anonymous function)

The line 63 is referencing the inline script. The jquery.js is included in the footer after this reference. Is there any way to make this work and leave the jQuery in the footer?

RegEdit
  • 2,060
  • 9
  • 36
  • 62
  • 1
    No, jQuery has to be loaded before you can use any jQuery. – j08691 Feb 19 '14 at 18:01
  • That makes sense. So, could this script could have used a native javascript call to determine when the document.ready is fired, then wrap jQuery call in that? – RegEdit Feb 19 '14 at 18:10

2 Answers2

1

The error is pretty clear, jQuery is not defined and therefore it can't be used. The simplest solution is to load the jQuery library before you call your inline code.

If you absolutely can't, you will have to use something different than jQuery(document).ready(...) That, by itself, is not a trivial matter and needs some careful thought (take a look at this SO question for some ideas)

I do notice that you're using jQuery(document).ready(...) and not $(document).ready(...) do you have a different framework loaded as well (mootools, prototype etc?) If so (and those libraries are being loaded earlier) you can simply hook into their equivalent of jQuery(document).ready(...)

Community
  • 1
  • 1
Code Magician
  • 21,032
  • 5
  • 55
  • 75
  • The script is loaded from a 3rd party plugin. I'm just trying to deal with it breaking my method of moving scripts from head to foot. – RegEdit Feb 19 '14 at 18:38
  • In that case, if you can't edit the code then you can't keep jQuery in the footer. I know it's increasing becoming best practice put your big scripts at the end of the page but it sounds like you don't have this luxury. – Code Magician Feb 19 '14 at 20:17
1

I have created a simple shim for this reason precisely. It creates a global jQuery (and $) object that are only capable of queuing functions for domReady. It is very tiny so you can inline it in the HEAD tag (inline to avoid the whole issue of a dns lookup, latency, etc) and then any code in the body written as you describe will still function properly.

https://github.com/withjam/jqshim-head

The shim essentially stores all of the functions passed to jQuery() or jQuery().ready(), waits for the real jQuery to be available, then passes them into the real jQuery() call to proceed with the isDomReady cycle.

Let me know if that helps.

Matt Pileggi
  • 6,688
  • 4
  • 14
  • 17