jQuery Document Ready Function For WordPress

Tento článek (nebo jeho část) je převzat z externího zdroje. Je tedy slušností jej uvést včetně případného autora.

You can set up a jQuery document ready function for use with WordPress and use the jQuery library that WordPress ships with rather than use another one. Here are three ways to use jQuery document ready function with WordPress.

Usually, a jQuery document ready function is expressed as below.

jQuery document ready 1st way

WordPress loads its own jQuery library in what is known as ‘no conflict mode‘ and the $ selector or variable that defines jQuery doesn’t work with the WordPress loaded jQuery version, so it has to be expressed more like so…

Here we are using jQuery at the beginning of the document ready function and then passing or binding that to the $ selector, so now anywhere else in the code you can use the $ selector.

jQuery document ready 2nd way

There is also a shorthand version of the jQuery document ready function.

Same issue here, using the jQuery at the beginning.

jQuery document ready 3rd way

Another way is to add the document ready code is inside a Javascript function…

The outer Javascript function is known as an anonymous function and jQuery is wrapped at the end, so is therefore aliased or bound to the $ selector, so in the inner function the jQuery shorthand document does not need to be aliased.

Add the Javascript where needed or register and enqueue the script for usage.