鍍金池/ 問答/Python  網(wǎng)絡(luò)安全  HTML/ 如何動(dòng)態(tài)prerender頁面?

如何動(dòng)態(tài)prerender頁面?

這幾天在看預(yù)加載的東東,有dns-prefetch,preconnect,prefetch,prerender。目前對(duì)最后一個(gè)prerender有興趣,可以預(yù)先加載整個(gè)頁面(相當(dāng)于后臺(tái)隱藏預(yù)添加一個(gè)tab)。
設(shè)想是這么做,在一個(gè)頁面中,當(dāng)鼠標(biāo)指向一個(gè)標(biāo)簽的時(shí)候,就在當(dāng)前頁面<head>添加預(yù)加載

<link rel="prerender" >

當(dāng)鼠標(biāo)離開的時(shí)候就把這個(gè)預(yù)加載標(biāo)簽刪除了:

$(document).ready(function() {
    $("a[href!='']").each(function() {
        $(this).on('mouseenter', function(event) {
            var pre_url = $(this).attr("href");
            $("link").each(function() {
                if (!($(this)[href=pre_url])) {
                    $("head").append('<link rel="prerender" href="' + pre_url + '">');
                }
            });
        });
        $(this).on('mouseleave', function(event) {
            var pre_url = $(this).attr("href");
            $("link").each(function() {
                if (!($(this)[href=pre_url])) {
                    $("head").remove('<link rel="prerender" href="' + pre_url + '">');
                }
            });
        });
    });
});

發(fā)現(xiàn)預(yù)加載的偏多了,而且移出鼠標(biāo)并不能刪除那個(gè)預(yù)加載

回答
編輯回答
膽怯

你的if (!($(this)[href=pre_url])) {}這個(gè)我沒看懂是什么意思,不是這樣判斷的
$('#a').remove();是直接刪除id=a你的用法不對(duì)
$("a[href!='']").each(function() {})多余了$("a[href!='']").on('mouseenter')會(huì)給所有選擇到的元素添加事件

$(document).ready(function() {
    $("a[href!='']").on('mouseenter', function(event) {
        var bool = false;
        var pre_url = $(this).attr("href");
        $("link").each(function() {
            if (($(this).attr("href")==pre_url)) {//判斷是否已經(jīng)存在存在則不添加
                bool = true
            }
        });
        if(!bool){
            $("head").append('<link rel="prerender" href="' + pre_url + '">');
        }
    });
    $("a[href!='']").on('mouseleave', function(event) {
        var pre_url = $(this).attr("href");//只要鼠標(biāo)移出就刪除 所有不用判斷
        $('link[href="' + pre_url +'"]').remove();
    });
});
2017年12月28日 15:45