Published on 09/16/2023
Published by amit
Adding 'Defer' attribute to Scripts added by Plugins in WordPress
How to add ‘defer‘ to scripts added by plugins in WordPress.
|
1 2 3 4 5 6 7 8 9 10 11 |
function wpoets_defer_scripts( $tag, $handle, $src ) { $defer = array( 'cff_carousel_js', 'cffscripts', 'ubermenu' ); if ( in_array( $handle, $defer ) ) { return '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n"; } return $tag; } add_filter( 'script_loader_tag', 'wpoets_defer_scripts', 10, 3 ); |
In this example, we are adding ‘defer’ ubermenu, cffscripts, and cff_carousel_js JavaScript files.
Here is another example.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function wpoets_defer_scripts( $tag, $handle ) { $scripts_to_defer = array( // pagination 'wpmtst-controller', 'dt-scripts-top', 'dt-custom-navscroll' ); if ( in_array( $handle, $scripts_to_defer ) ) { return str_replace( ' src', ' defer src', $tag ); } return $tag; } add_filter( 'script_loader_tag', 'wpoets_defer_scripts', 10, 2 ); |
Just remember to add this code to either a site-specific plugin or the functions.php file in the theme.
|
1 2 |
script type="text/javascript" src="/wp-includes/js/hoverintent-js.min.js?ver=2.2.1" id="hoverintent-js-js"></script> <script type="text/javascript" src="/wp-includes/js/admin-bar.min.js?ver=6.8.1" id="admin-bar-js"></script> |
The “$scripts_to_defer” or “$defer” array contains the ‘admin-bar’ part from the id=”admin-bar-js” in the example script above.