script_loader_tag 函数是如何工作的? [英] How does the script_loader_tag function works?

查看:15
本文介绍了script_loader_tag 函数是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到在functions.php、WordPress中应用了script_loader_tag函数,但我很难完全理解它是如何工作的.

I have seen script_loader_tag function applied in functions.php, WordPress, but I struggle to understand completely how does it work.

例如,我见过这样的例子:

For example, I've seen examples like this:

function add_async_defer($tag, $handle) {

    if('googlemaps' !== $handle) {
        return $tag;
    }
    return str_replace(' src', 'async="async" defer="defer" src', $tag);
}
add_filter('script_loader_tag', 'add_async_defer', 10, 2);

它用于为 Google Maps API 生成脚本标签:

and it is used to generate the script tag for Google Maps API:

<script type='text/javascript'async="async" defer="defer" src='https://maps.googleapis.com/maps/api/js?key=AIzaSyBz02VRxO_dgaKsBS62TLL6AW4McNTQiKU&#048;callback=initMap&#038;ver=5.2.1'></script>

但是 $tag 和 $handle 参数是什么意思?

But what does the $tag and $handle parameters mean?

add_filter 末尾的数字 10 和 2 是什么意思?

What does numbers 10 and 2 mean in the end of the add_filter?

这个功能可以修改为只在特定页面有条件地显示标签吗?

Can this function be modified to display the tag conditionally only in the specific pages?

推荐答案

参数定义如下:

$tag:排队脚本的标签.

$handle:脚本的注册句柄.例如,WordPress 入队的 jQuery 的句柄为 'jquery'

$handle: The script's registered handle. For example the jQuery enqueued by WordPress has the handle 'jquery'

数字 10 表示 WordPress 队列中回调函数的优先级,以处理挂在 script_loader_tag 钩子上的所有函数.

The numeric 10 represents the priority of the callback function in WordPress queue to process all the functions hooked on the script_loader_tag hook.

数字2表示回调函数中允许的参数个数.

The numeric 2 represents the number of parameters allowed in callback function.

@chinLeung 也给出了参考答案.

@chinLeung answered with reference as well.

考虑到您的代码示例,以下内容应进一步解释:

Considering your code example the following should explain things further:

function add_async_defer($tag, $handle, $src) {
    if('googlemaps' !== $handle) {//Here we check if our handle is googlemaps
        return $tag; //We return the entire <script> tag as is without modifications.
    }
    return "<script type='text/javascript' async='async' defer='defer' src='".$src."'></script>";//Usually the value in $tag variable looks similar to this script tag but without the async and defer
}
add_filter('script_loader_tag', 'add_async_defer', 10, 3);

这篇关于script_loader_tag 函数是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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