Advanced JavaScript loading

The module based approach you’ve seen in CSS and PHP extends to JavaScript as well. There is no central location where all JavaScript files are enqueued conditionally. Instead, they are enqueued by the PHP components using those scripts. That way, each component is compartmentalized and self-sustaining.

A good example of this is the accessibility component, which uses a JavaScript file to ensure the main menu is accessible for all input devices, including keyboard, touch, and mouse.

The file in question is navigation.js, which sits under ‘assets’ and ‘js’. The reason it sits there is because the build process needs to be able to get its hands on the JavaScript files and compile them out. And that all happens inside the assets folder.

The component that enqueues this file is found under the “inc” folder and “Accessibility”.

The component first calls the initialize function and triggers add_action(), wp_enqueue_scripts(), and points to a custom function. Apart from the initialize function, this is the standard way of calling wp_enqueue_scripts() and calling in custom scripts and invocations. The only difference is that in WP Rig, this is placed inside the component. In other themes, it’s usually placed inside the functions.php file in a long list.

The action_enqueue_navigation_script() function that was just called with the add action() call contains the standard wp_enqueue_scripts() invocation. Here we used wp_enqueue_scripts() exactly how you would always use it.

But this is the old way of loading script. The web has moved past this best practice, and WP Rig now allows you to load scripts in the modern way. Traditionally, JavaScript was loaded at the bottom of a document to avoid rendering conflicts. Modern JavaScript has done away with this practice, thanks to the “async” and “defer” attributes, and the ability to precache script files.

“Async” and “defer” allow us to load script files in the <head> section of the document, and then either tell the browser to run the script asynchronously (when the file is fully loaded), or defer running the script until everything else is in place.

WP Rig has custom functionality allowing you to declare either “async” or “defer” for each individual script you enqueue. So you can choose exactly what you want to happen to each individual script.

This is cutting edge and not yet supported in WordPress, but this code will be supported at some point in the future, and you will not run into any conflicts.

More from this course: