WordPress
JavaScript
page load optimization
defer async
web performance

How do I defer or async this WordPress javascript snippet to load lastly for faster page load times?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Understanding JavaScript Loading in WordPress

Improving the performance of a WordPress site often involves optimizing how JavaScript is loaded. Deferring or asynchronously loading JavaScript scripts can significantly boost your page load times by ensuring these scripts do not block the rendering of your content. This article dives into how you can defer or async a WordPress JavaScript snippet to enhance loading times effectively.

Why Defer or Async JavaScript?

JavaScript files can slow down your website because they are typically render-blocking. This means the browser has to stop downloading and rendering other elements on the page while it processes the JavaScript file. By deferring or loading scripts asynchronously, you allow the HTML and other assets to load first, enhancing the viewer's perceived performance of your site.

  • Defer: This attribute tells the browser to continue downloading the HTML content while the JavaScript is being fetched. The JavaScript will execute once the HTML is fully parsed.
  • Async: This attribute also allows the browser to download the script while the HTML is being parsed, but the script will be executed immediately after it is downloaded, potentially before the HTML is completely parsed.

How to Implement Defer or Async in WordPress

WordPress provides hooks and filters to modify various parts of your theme and plugins. You can use these features to add attributes to your script tags. Here's a step-by-step guide.

Step 1: Register and Enqueue Your Script

First, you need to register and enqueue your script using wp_enqueue_script in your theme's functions.php file.

php
1function custom_enqueue_scripts() {
2    wp_register_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array(), null, true);
3    wp_enqueue_script('custom-script');
4}
5add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');

The null parameter is for the version (optionally, this can be set), and the true parameter ensures the script is loaded in the footer.

Step 2: Add Defer or Async Attribute

Next, you can add a filter to append the defer or async attribute to your registered script.

php
1function add_defer_attribute($tag, $handle) {
2    // add script handles to the array below
3    $scripts_to_defer = array('custom-script');
4
5    if (in_array($handle, $scripts_to_defer)) {
6        return str_replace(' src', ' defer="defer" src', $tag);
7    }
8    return $tag;
9}
10add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);

To add async instead, replace defer="defer" with async="async" in the str_replace function.

Step 3: Test Your Changes

It's crucial to test your changes to ensure JavaScript functionality has not been disrupted. Consider using tools like Google PageSpeed Insights or GTmetrix to verify improvements in load times.

Summary

Loading StrategyCharacteristicsUsage
BlockingJavaScript pauses other loading tasks until it's fully downloaded and executed.Not recommended unless necessary scripts are crucial for initial page render.
deferJavaScript downloads with HTML parsing and waits to execute until HTML is fully loaded.Ideal for scripts that don't alter content structure or initial view.
asyncJavaScript downloads with HTML parsing and executes immediately upon completion.Suitable for independent scripts that do not rely on other DOM elements.

Additional Considerations

  1. Script Dependencies: Ensure that scripts dependent on others (e.g., jQuery plugins) are loaded in the correct order. The defer attribute is preferable in such cases.
  2. Conditional Loading: For scripts needed only on specific pages, use conditional tags in WordPress to load scripts conditionally.
  3. Third-Party Scripts: If you're working with third-party scripts, check their documentation, as some may not work well with defer or async.
  4. WordPress Plugins: Numerous WordPress plugins can automate script optimization, offering features like script combination, minification, and asynchronous/deferred loading.

Conclusion

Optimizing JavaScript loading by deferring or asynchronously loading scripts can yield significant performance improvements. By carefully implementing these methods, you can ensure that your website is fast, responsive, and fully functional for all visitors.

By understanding how to utilize these options properly, you'll ensure faster loading times and a better user experience on your WordPress site.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms