3

I read How to add defer="defer" tag in plugin javascripts? and the code @toscho posted works good to defer certain js files or deferring ALL js files by commenting out the contact-form-7 line, but I need to defer all js except 1 or 2 files. I for sure need to exclude jquery.min because it causes the Revolution Slider plugin to stop working when it's deferred.

So how would I write a conditional in the following code to exclude certain js files? For example if I wanted to exclude jquery.min and jquery.ui.core.min

function add_defer_to_cf7( $url )
    {
        if ( // comment the following line out add 'defer' to all scripts
        FALSE === strpos( $url, 'contact-form-7' ) or
        FALSE === strpos( $url, '.js' )
        )
        { // not our file
            return $url;
        }
        // Must be a ', not "!
        return "$url' defer='defer";
    }
    add_filter( 'clean_url', 'add_defer_to_cf7', 11, 1 );
1
  • tumbleweeds No one? :)
    – Nate M.
    Commented Apr 3, 2014 at 2:52

2 Answers 2

4

I supposed that you are trying to set defer for every JS exclude jquery.min and jquery.ui.core.min.

Based on that I have made some changes into your code and this will set defer for all JS exclude given example files jquery.min and jquery.ui.core.min.

function add_defer_to_cf7( $url )
{
    //If  not js file OR js file with 'jquery.ui.core.min' OR 'jquery.min' name string, then no need to apply defer
    if(FALSE === strpos( $url, '.js') || ((strpos( $url, 'jquery.ui.core.min') > 0) || (strpos($url, 'jquery.min') > 0))){ 
        return $url;
    }
    else{
        //set defer for .js files
        return "$url' defer='defer";        
    }
}
add_filter( 'clean_url', 'add_defer_to_cf7', 11, 1 );

Above code set defer='defer' for all JS excluding 'jquery.ui.core.min' and 'jquery.min' and this is what you want. Good luck!

Thanks!

2
  • And where should I put this function? Commented Oct 24, 2015 at 3:15
  • 1
    Please put this code into your current/active theme function.php file. Commented Oct 26, 2015 at 8:05
1

I am using this code, i Hope it helps you.

function defer_parsing_of_js ( $url ) {
    if ( FALSE === strpos( $url, '.js' ) ) return $url;
    if ( strpos( $url, 'jquery.min.js' ) ) return $url;
    return "$url' defer='defer";
  }
add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.