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

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

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

<link rel="prerender" >

當鼠標離開的時候就把這個預(yù)加載標簽刪除了:

$(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ù)加載的偏多了,而且移出鼠標并不能刪除那個預(yù)加載

回答
編輯回答
膽怯

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

$(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");//只要鼠標移出就刪除 所有不用判斷
        $('link[href="' + pre_url +'"]').remove();
    });
});
2017年12月28日 15:45