Chapter 9. Advanced Events

Ariel Flesler

Introduction

These recipes will deal with edge case problems, advanced optimizations, and certain techniques to make your code cooler. These recipes are mostly for advanced developers who want to take their jQuery code one step further.

As in Chapter 8, I’ll refer to code as plugins, but that doesn’t mean it needs to be an actual plugin. If you don’t structure your code as jQuery plugins, then keep my naming convention in mind.

9.1. Getting jQuery to Work When Loaded Dynamically

Problem

You are including jQuery dynamically into the page, by either adding a <script> element to the DOM or doing it some other way like Ajax.

Once jQuery is loaded, you expect everything to start working, but for some reason, no script starts.

Solution

You need to include an additional script to be executed after jQuery is loaded. This script will simply call jQuery.ready(). After you do this, everything will start working as expected.

Discussion

What is jQuery.ready()?

The jQuery.ready() function is called by jQuery’s core when the document is detected as ready. Once called, all the document.ready handlers are triggered automatically.

Note

You don’t need to worry about whether this function might have been called already (for example, by the original detection), triggering all the document.ready handlers again.

jQuery.ready() includes a check for duplicated executions internally. Further calls will be ignored.

Why was this happening?

The document.ready detection is mostly based ...

Get jQuery Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.