1

I'm loading jquery defered to not get problems with pagespeed. However now it may happen what my script is executed before jQuery even is loaded. This leeds to errors like function jQuery not defined. How can I ensure that jQuery is loaded?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Manuel
  • 9,112
  • 13
  • 70
  • 110
  • 3
    um.. like, not to use deferred? – MightyPork Jul 11 '14 at 21:48
  • 1
    You can use an async loader like require.js, but this probably means rethinking the whole code. Why don't you try moving the jQuery inclusion to the bottom of the page, and your script just after jQuery? You can wrap everything in the document ready event. – ffflabs Jul 11 '14 at 21:56
  • Load all of your scripts deferred, after jquery. Note, if you're code is at the bottom or deferred, you don't need the document ready event. – Kevin B Jul 12 '14 at 02:14
  • @amenadiel - Your suggestion to move the scripts (and remove the defer attribute) to the bottom of the page is a good idea. One thing, though - if your jQuery script (and your own script) are at the bottom of the page - then you don't need to use `document.ready`. The constant use of wrapping code in the `document.ready` event when it's not necessary is probably one of the most annoying widespread (anti)patterns in the jQuery community. – Adam Jenkins Jul 12 '14 at 02:17

1 Answers1

1

You don't show the code you're using for loading jQuery deferred, but if you want to load it that way, then you have to trigger any of your code that uses jQuery by some sort of onload callback that gets called when jQuery has successfully loaded.

All your code that uses jQuery upon page load will then have to be initially called from something that is called from this onload handler. You won't be able to just use $(document).ready() directly until after jQuery is loaded.

If you include the code you're using to load jQuery, we can be more specific about how to know when it's loaded. There are libraries to handle that for you, but it's also not a lot of code to just code it yourself.

For example, if you're using the defer attribute in a <script> tag and you're OK with IE9 or higher, then you can do this:

<script>
function jQueryLoaded() {
    // put your page initialization code that uses jQuery here
    // or call some other functions that do your page initialization
}
</script>
<script defer="defer" onload="jQueryLoaded()" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

If you want cross browser compatibility even further back than IE9, then you should probably dynamically add the script tag so you can monitor it in older versions of IE with the readystatechange event handler. See the loadScript() function in this post for details.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979