Defer JS on WordPress
Posted by Nuno Marques on 20 Feb 2019
Introduction
JavaScript plays a crucial role in modern web development, but it can also impact page loading times, especially when scripts are loaded synchronously. By deferring JavaScript execution, you can prioritize the loading of critical content, resulting in faster page rendering and improved user experience. In this post, we'll explore a simple method to defer JavaScript on WordPress websites.
Tutorial
<?php // Defer JS
function defer_parsing_of_js($url) {
if (is_admin()) return $url;
if (false === strpos($url, '.js')) return $url;
if (strpos($url, 'jquery.js')) return $url;
return str_replace(' src', ' defer src', $url);
}
add_filter('script_loader_tag', 'defer_parsing_of_js', 10);
?>
Explanation
The provided PHP function defer_parsing_of_js
modifies the HTML script tags for JavaScript files, adding the defer
attribute to defer their execution. This ensures that JavaScript files are loaded asynchronously, allowing other page content to load without waiting for scripts to execute.
How It Works
- The function checks if the current request is in the WordPress admin area. If so, it returns the original script URL unchanged.
- It then checks if the script URL contains ".js". If not, it also returns the URL unchanged.
- Additionally, it excludes jQuery scripts from being deferred to prevent compatibility issues.
- Finally, it replaces the "src" attribute with "defer src" to defer script execution.
Benefits
Deferring JavaScript can significantly improve page loading speed, particularly for websites with multiple scripts. By prioritizing the loading of critical content, users can access the main page elements faster, enhancing user experience.
Conclusion
Implementing JavaScript deferment on WordPress can lead to substantial improvements in website performance, resulting in faster loading times and better user engagement. By following the simple method outlined in this post, you can optimize your WordPress website for optimal performance.