It is common to use toc.js
, a JavaScript file, to
automatically generate a Table of Contents (TOC) on a WordPress site. However, there are cases where toc.js
does not work properly. The main reason for this may be that jQuery
is not loaded correctly. This section describes how to solve this problem.
Why is the loading order of jQuery important?
Because toc
.
js
depends on the jQuery library, if jQuery is not loaded first, an error will occur and toc.js
will not work properly. jQuery uses the symbols $ and
jQuery
, so toc.js
will not work unless these are available Solution: jQuery is not loading correctly.
Solution: make sure jQuery is loaded.
- Open the
header.php and
functions.php
files of your WordPress theme and check thatjQuery
is loaded correctly. - Check the loading order and set it so that
jQuery
is loaded beforetoc.js
. - To load jQuery, use the
wp_enqueue_script
function infunctions.php
. For example, write the following
function enqueue_custom_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('toc-js', get_template_directory_uri() . '/js/toc.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
This code specifies jQuery
as a toc.js
dependency, so jQuery
is always loaded first.
Troubleshooting: How to check
You can also use the developer tools to check the loading order of jQuery and toc.js
. Check for errors in the Console
tab and recheck the loading order if you see errors such as jQuery is not defined
.