Using Javascript in WordPress Themes

If you’re planning to use javascript on your WordPress blog or website, there is one function with which you should become intimately familiar. That function is wp_enqueue_script(). It will also be helpful if you do a little bit of research into the wp_deregister_script() function, though, the only official information you’ll find about that function is in the codex information about the wp_enqueue_script() function.

Basically, this function keeps a log of all of the javascript files and libraries you want to use in your theme, makes sure you aren’t duplicating any, and then outputs them in the right order. I would recommend setting the $in_footer parameter to boolean true for all of the scripts you enqueue, as that causes WordPress to add the javascript calls to the footer of your pages rather than putting them in the header. In order to do this, though, you need to make sure that you include the wp_footer() function inside of your theme (preferably just above the closing </body> tag).

However, even if you do output the script in the footer of your theme, all of your scripts need to be enqueued before the wp_head() function is called. Therefore, if you plan to add any scripts to the queue throughout the bodies of your pages, you will need to either plan for those instances in the header of your theme file, or you’ll need to implement some output buffering within your theme files. Both methods obviously have their advantages and disadvantages. Trying to anticipate your script usage before you even invoke the header can be extremely difficult (especially if you have a lot of different scripts for different conditions on your WordPress site), but output buffering will cause major issues for you if you have large pages or posts (the output buffer will cause a fatal error if your PHP installation runs out of memory to store the buffer).

You can find a little more information about using the wp_enqueue_script() function in real-world situations on the Lost in Code blog.

Once you get the hang of the wp_enqueue_script() function, you’ll want to move onto reviewing and utilizing the wp_enqueue_style() function. Just as the wp_enqueue_script() function adds javascript files to a queue to be output all at once; the wp_enqueue_style() function does the same thing with CSS files.