Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress - Add sync defer tag in wp_enqueue_style CSS Files

Tags:

wordpress

I need to add sync or defer attribute in Stylesheets CSS file which are included by using wp_enqueue_style.

My Code is below.

function my_scripts() {
  wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.css', array(), '4.4.2');
  wp_enqueue_style('my-style', get_stylesheet_uri());
  wp_enqueue_style('about-page', get_template_directory_uri() . '/css/about-styles.css', array(), '4.4.3');
  wp_enqueue_script('bootstrap-min', get_template_directory_uri() . '/js/bootstrap.min.js', array(), '20151112', true);
  wp_enqueue_script('jquery-scrollto', get_template_directory_uri() . '/js/jquery-scrollto.js', array(), '20112', true);
  wp_enqueue_style('details-pages', get_template_directory_uri() . '/css/details-pages.css', array(), '4.4.3');
  wp_enqueue_style('owl-carousel-css', get_template_directory_uri() . '/css/owl/owl.carousel.css', array(), '4.4.2');
  wp_enqueue_script('owl-carousel-js', get_template_directory_uri() . '/css/owl/owl.carousel.min.js', array(), '202', true);
  wp_enqueue_script('scripts-js', get_template_directory_uri() . '/js/scripts.js', array(), '20151112', true);
}

add_action('wp_enqueue_scripts', 'my_scripts');

Now I want to add sync or defer attribute in different CSS Style sheets. So please help me, how to add sync or defer attribute. I want to add attributes in just CSS files not in JavaScript files.

Any help will be appreciated.

Thanks.

like image 915
John Brad Avatar asked Sep 02 '25 09:09

John Brad


1 Answers

Try this code

function add_custom_attr( $tag, $handle, $src ) {
    $scriptArr = array('bootstrap','my-style','about-page','bootstrap-min','jquery-scrollto','details-pages','owl-carousel-css','owl-carousel-js','scripts-js');

    if (in_array($handle, $scriptArr)) {
    $tag = str_replace( 'src=', 'sync="false" src=', $tag );
    }
    return $tag;
}
add_filter( 'script_loader_tag', 'add_custom_attr', 10, 3 );
like image 84
Vel Avatar answered Sep 05 '25 00:09

Vel