具有完整性和跨域的Wordpress脚本 [英] Wordpress script with integrity and crossorigin

查看:224
本文介绍了具有完整性和跨域的Wordpress脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在WordPress上使用wp_register_script和wp_enqueue_script FUNCTION来使脚本入队,该脚本具有两个属性:完整性"和"crossorigin".

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".

通常我使用PHP,我的代码如下:

Normally I use PHP and my code looks like:

wp_register_script('jquery', 'http' . ($_SERVER['SERVER_PORT'] == 443 ? 's' : '') . '://code.jquery.com/jquery-3.1.1.slim.min.js', false, null);
wp_enqueue_script('jquery');

使用任何其他脚本. wp_register_script具有五个参数(在本例中为四个)$ handle,$ src,$ deps,$ ver($ media).我想知道在哪里可以添加两个属性.我已经尝试过:

With any other script. The wp_register_script takes five parameters (in this case four) $handle, $src, $deps, $ver ($media). I'm wondering where I can add the two attributes. I've already tried:

wp_register_script('jquery', 'http' . ($_SERVER['SERVER_PORT'] == 443 ? 's' : '') . '://code.jquery.com/jquery-3.1.1.slim.min.js'.'integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n"', false, null);
    wp_enqueue_script('jquery');

但这没用.

有人遇到同样的问题吗? 这是Bootstrap 4的原始脚本,该脚本也具有Bootstrap和Tether,它们具有相同的属性(完整性和跨域),因此,由于它非常新,因此非常感谢任何帮助.

Anyone who had the same problem? This is the original script from bootstrap 4, which also has bootstrap and tether with the same attributes (integrity and crossorigin) so, since it is pretty new, any kind of help will be very appreciated.

推荐答案

您可以使用 script_loader_tag 钩子(主要部分实际上不是我的代码,但老实说我不记得我从哪里得到了它,可能在SO或WP Stack Exchange上的某个位置):

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 '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n";
}
if ( in_array( $handle, $async_scripts ) ) {
    return '<script src="' . $src . '" async="async" type="text/javascript"></script>' . "\n";
}
if ( in_array( $handle, $jquery ) ) {
    return '<script src="' . $src . '" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous" type="text/javascript"></script>' . "\n";
}
return $tag;
} 

这篇关于具有完整性和跨域的Wordpress脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆