半夏凉歌   还在忙吗,别忘了给自己一个微笑。   2022-12-02

想必很多人还不了解DNS Prefetch是什么

官方说明是:

Prefetches DNS lookups to speed up browsing

—意思是,预先读取(查询)DNS,以加快浏览.

既然有这个方法,不需要插件为什么不加上呢

首先在functions.php文件中加上以下代码:

<?php
function set_newuser_cookie() {
if (!isset($_COOKIE['banxia_cookie'])) {
setcookie('banxia_cookie', 1, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false);
}
}
add_action('after_setup_theme', 'set_newuser_cookie');
?>

然后在主题文件夹下新建一个dns.php文件并加入以下代码:

<?php
if (is_home()) { //判断当前页面是否为首页
    echo '
<meta http-equiv="x-dns-prefetch-control" content="on" /> //开启dns预取
<link rel="dns-prefetch" href="//hm.baidu.com" />
<link rel="dns-prefetch" href="cpro.baidustatic.com" />
<link rel="dns-prefetch" href="//pos.baidu.com" />
<link rel="dns-prefetch" href="//a.alimama.cn" />
<link rel="dns-prefetch" href="//wn.pos.baidu.com" />
<link rel="dns-prefetch" href="//g.click.taobao.com" />
<link rel="dns-prefetch" href="//acookie.taobao.com" />
<link rel="dns-prefetch" href="//hz.mmstat.com" />
<link rel="dns-prefetch" href="//strip.taobaocdn.com" />
<link rel="dns-prefetch" href="//gaitaobao4.alicdn.com" />
<link rel="dns-prefetch" href="//img04.taobaocdn.com" />
<link rel="dns-prefetch" href="//dup.baidustatic.com" />
    ';
}
           
    elseif (isset($_COOKIE['banxia_cookie'])) { //判断是否为初次访问
        echo '<meta name="author" content="WordPress Dns Prefetch Is By BanXia" />
';
            }
        else        {
        echo '
<meta http-equiv="x-dns-prefetch-control" content="on" />
<link rel="dns-prefetch" href="//hm.baidu.com" />
<link rel="dns-prefetch" href="cpro.baidustatic.com" />
<link rel="dns-prefetch" href="//pos.baidu.com" />
<link rel="dns-prefetch" href="//a.alimama.cn" />
<link rel="dns-prefetch" href="//wn.pos.baidu.com" />
<link rel="dns-prefetch" href="//g.click.taobao.com" />
<link rel="dns-prefetch" href="//acookie.taobao.com" />
<link rel="dns-prefetch" href="//hz.mmstat.com" />
<link rel="dns-prefetch" href="//strip.taobaocdn.com" />
<link rel="dns-prefetch" href="//gaitaobao4.alicdn.com" />
<link rel="dns-prefetch" href="//img04.taobaocdn.com" />
<link rel="dns-prefetch" href="//dup.baidustatic.com" />
    ';
            }
?>

然后在主题的header.php文件的</head>标签之前加入以下代码:
include TEMPLATEPATH. '/dns.php';
好了这样一来wordpress将只在首页和访客初次访问的时候显示dns预取标签了(PS:预取域名可以按照自己网站的具体需求去设置)。