Search code examples
wordpresspagespeed

Data attributes in wordpress wp_register_script and pagespeed


I would like to load the most of my javascripts async to speed up the rendering. Sadly defer is breaking a lot of parts of my wordpress website and i need to exclude it from async load. One file of my theme is using the code

    wp_register_script( 'tie-masonry',      get_template_directory_uri() . '/js/isotope.js',            array( 'jquery' ),  false, true );

Pagespeed is needing the attribute data-pagespeed-no-defer Like <script data-pagespeed-no-defer>...</script> to exclude it.

Is it possible to add this attribute to the wp_register_script, or do i need to exclude it from the php file and insert it by hand into the webpage?


Solution

  • Since 4.1.0 there is a filter hook 'script_loader_tag', which is perfect for this task.

    add_filter( 'script_loader_tag', 'my_script_loader_tag', 10 ,2 );
    function my_script_loader_tag( $tag, $handle ){
        if ( $handle == 'tie-masonry' ) {
            return str_replace( '<script', '<script data-pagespeed-no-defer', $tag );
        }
        return $tag;    
    }