Wordpress script with integrity and crossorigin

前端 未结 7 1181
旧时难觅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:36

    This is well explained here:

    • https://snippets.webaware.com.au/howto/subresource-integrity-wordpress-scripts-stylesheets/
    • https://developer.wordpress.org/reference/functions/wp_enqueue_script/#comment-4246

    For each enqueued script you need to add a filter which adds proper attributes;

    /**
    * load custom JS
    */
    add_action('wp_enqueue_scripts', function() {
        wp_enqueue_style('jquery', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js', [], null);
    
        add_filter('style_loader_tag', __NAMESPACE__ . '\\add_jquery_sri', 10, 2); 
    });
     
    /**
    * add SRI attributes to jQuery style loader element
    
    * @param string $html
    * @param string $handle
    * @return string
    */
    function add_jquery_sri($html, $handle) {
        if ($handle === 'jQuery') {
            $html = str_replace(' />', ' integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous" />', $html);
        }
     
        return $html;
    }
    

    URL & hash taken from https://cdnjs.com/libraries/jquery All praise to the authors!

提交回复
热议问题