Skip to content

Instantly share code, notes, and snippets.

@Antoinebr
Created April 18, 2018 15:34
Show Gist options
  • Save Antoinebr/acbbf9678fc59c8bcf6c8696438204d1 to your computer and use it in GitHub Desktop.
Save Antoinebr/acbbf9678fc59c8bcf6c8696438204d1 to your computer and use it in GitHub Desktop.
<?php
/*
| --------------------------------------------------------------------------
| DEFER on scripts
| function to add async and defer attributes
| --------------------------------------------------------------------------
*/
function defer_js_async($tag){
## 1: list of scripts ( by file name) 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',
'cookie.js',
'autocomplete',
// WooCommerce
'add-to-cart.min.js',
'cart-fragments.min.js',
'jquery.cookie.min.js',
'jquery.blockUI.min.js',
'woocommerce.min.js',
'single-product.min.js',
// Wordpress
'wp-embed.min.js'
);
// If we want to defer scripts only on some pages ( here jQuery only on the home page )
if( is_front_page() ) $scripts_to_defer[] = "jquery.js";
#defer scripts we add the defer attribute to the scripts
foreach($scripts_to_defer as $defer_script){
if(strpos($tag, $defer_script ) ){
return str_replace( ' src', ' defer="defer" src', $tag );
}
}
return $tag;
}
if(!is_admin() && !is_user_logged_in()) {
add_filter( 'script_loader_tag', 'defer_js_async', 10 );
}
<?php
/*
| --------------------------------------------------------------------------
| CSS management
| Remove some CSS files from specific pages : front-page / product page / category / offline
| --------------------------------------------------------------------------
*/
add_filter( 'style_loader_tag', function($tag){
// list of CSS to remove
$cssToRemove = array();
// condition : which pages
if(
is_front_page()
|| is_product()
|| is_product_category()
|| is_page_template( 'template-offline.php')
){
// We push in the array a list of CSS files to remove
array_push($cssToRemove,
"woocommerce.css",
"woocommerce-smallscreen.css",
"woocommerce-layout.css",
"titan-framework-flux-settings-css"
);
}
// For each Style we check if it must be excluded
foreach($cssToRemove as $css){
if(strpos($tag, $css ) ) return false;
}
return $tag;
}, 10 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment