沃梦达 / 编程问答 / php问题 / 正文

具有完整性和跨域性的 Wordpress 脚本

Wordpress script with integrity and crossorigin(具有完整性和跨域性的 Wordpress 脚本)

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

问题描述

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

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 和具有相同属性(完整性和跨域)的系链,因此,由于它很新,任何形式的帮助都将不胜感激.

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

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

本文标题为:具有完整性和跨域性的 Wordpress 脚本

基础教程推荐