Wordpress script with integrity and crossorigin

前端 未结 7 1182
旧时难觅i
旧时难觅i 2021-02-03 12:07

I\'m trying to use the wp_register_script and wp_enqueue_script FUNCTION on WordPress to enqueue a script, which has two attributes: \"integrity\" and \"crossorigin\".

N

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-03 12:22

    You can use the script_loader_tag hook (the main part is actually not my code, but I honestly don't remember where I got it, probably somewhere here on SO or WP Stack Exchange):

    add_filter( 'script_loader_tag', 'add_attribs_to_scripts', 10, 3 );
    function add_attribs_to_scripts( $tag, $handle, $src ) {
    
    // The handles of the enqueued scripts we want to defer
    $async_scripts = array(
        'jquery-migrate',
        'sharethis',
    );
    
    $defer_scripts = array( 
        'contact-form-7',
        'jquery-form',
        'wpdm-bootstrap',
        'frontjs',
        'jquery-choosen',
        'fancybox',
        'jquery-colorbox',  
        'search'
    );
    
    $jquery = array(
        'jquery'
    );
    
    if ( in_array( $handle, $defer_scripts ) ) {
        return '' . "\n";
    }
    if ( in_array( $handle, $async_scripts ) ) {
        return '' . "\n";
    }
    if ( in_array( $handle, $jquery ) ) {
        return '' . "\n";
    }
    return $tag;
    } 
    

提交回复
热议问题