Last active
December 20, 2017 07:24
-
-
Save Antoinebr/e87fe0bca80bf24a36bce76c4288481a to your computer and use it in GitHub Desktop.
defer-wp-scripts.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
function to add async and defer attributes | |
Will only work if the scripts are enqueued with wp_enqueue_script() | |
*/ | |
function defer_js_async($tag){ | |
## 1: list of scripts to defer. | |
$scripts_to_defer = array( | |
'owl-carousel.min.js', | |
'mansonry.js', | |
'imgloaded.js', | |
'jquery.magnific-popup.min.js', | |
'bgswitcher.js', | |
'exit.js', | |
'lazyload.js', | |
'app.js', | |
// WooCommerce | |
'add-to-cart.min.js', | |
'cart-fragments.min.js', | |
'jquery.cookie.min.js', | |
'jquery.blockUI.min.js', | |
'woocommerce.min.js', | |
// Wordpress | |
'wp-embed.min.js' | |
); | |
#defer scripts | |
foreach($scripts_to_defer as $defer_script){ | |
if(true == strpos($tag, $defer_script ) ) | |
return str_replace( ' src', ' defer="defer" src', $tag ); | |
} | |
return $tag; | |
} | |
// You can wrap this hook is a wp_is_mobile() function if you want this behavior only on mobile | |
add_filter( 'script_loader_tag', 'defer_js_async', 10 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment