Add Snippet To Project
For web development and WordPress users, efficiently managing how your website loads can play a crucial role in optimizing its overall performance. One often overlooked place of improvement is in the handling of query variables and version numbers from your site’s scripts and styles. Unnecessarily loading these can increase your site’s load time, impacting user experience and SEO. In this article, we will explore how to remove these versions and eliminate this unnecessary loading, thereby giving your website an immediate performance boost.
function wpturbo_remove_script_version( $src ){
return remove_query_arg( 'ver', $src );
}
add_filter( 'style_loader_src', 'wpturbo_remove_script_version', 15, 1 );
add_filter( 'script_loader_src', 'wpturbo_remove_script_version', 15, 1 );
Our code snippet aims at removing the version query string from script and style resources. This is especially useful for performance optimization since it may aid in caching the files.
The initial part of the provided script defines a function, wpturbo_remove_script_version($src)
. The $src
argument represents the source URL of the enqueued script or style.
Inside this function, we call another function, remove_query_arg('ver', $src)
. The remove_query_arg()
function is a built-in WordPress function that removes query arguments from a URL. In our case, it removes the ‘ver’ query argument, which stands for version.
So, when the function wpturbo_remove_script_version($src)
is called, it will return the source URL of a script or a style but without the version query string.
The last two lines of provided script add this newly defined function, wpturbo_remove_script_version($src)
, as a filter on two WordPress hooks: style_loader_src
and script_loader_src
.
add_filter( 'style_loader_src', 'wpturbo_remove_script_version', 15, 1 );
add_filter( 'script_loader_src', 'wpturbo_remove_script_version', 15, 1 );
What this code does is, it effectively tells WordPress to apply the function wpturbo_remove_script_version
whenever it loads styles and scripts.
The add_filter
function accepts four parameters, but in this case, only three of them are used.
The first parameter is the name of the filter hook, style_loader_src
, indicating that the function is to be applied while styles are loaded. The second parameter is the name of the function to be executed.
The third parameter sets the priority of the function as it is the order in which functions hooked to this event are executed. The lower the number, the earlier the function gets executed. Here, it’s set to 15.
The last parameter would specify the number of parameters the function accepts. In this case, we don’t specify it because the default is 1, which is the number of parameters wpturbo_remove_script_version
accepts.
Thus by using this snippet, you can remove the version parameters from the URLs of enqueued scripts and styles, potentially improving the caching mechanisms of browsers and speed up your website.