Firefox add-on prefetching with link tag

邮差的信 提交于 2019-12-13 19:28:25

问题


I'm trying to create a simple Firefox add-on to prefetch some webpages. I'd like to use Firefox's link tag to do the prefetching, since it seems like that's the easiest way. Here's my code:

main.js:

exports.main = function() {
    var commentFinder = pageMod.PageMod({
        include: "*",
        contentScriptFile: data.url("prefetch.js"),
        attachTo: ["top"],
        onAttach: function(worker) {
            worker.port.emit("init");
        }
    });
}

prefetch.js:

var start = '<link rel="prefetch" href="';
var end = '">'
var links = [];
var aTags = document.body.getElementsByTagName("a")

for(var i=0; i<aTags.length; i++){
    var href = aTags[i].getAttribute("href");
    if(links.indexOf(href) == -1) 
        links.push(href);
}

for(var i=0;i<links.length;i++){
    console.log(links[i]);
    var tag = start + String(links[i]) + end;
    document.head.innerHTML = tag + document.head.innerHTML;
}

When I include the link tags in the HTML of the pages I request, they get prefetched, but when I add in link tags using the add-on, they don't. I think the problem might be when Firefox is checking for the link tag, but I'm not sure. Is there any way to test/fix this?


回答1:


I looked through the code, and it appears that <link rel="prefetch"> elements are only processed when the parser is still active (see the call graph of ProcessLink(hg)). Hence it works when using an inline script in a web site, but not using a regular page-mod.

You may try to attach the script earlier, i.e add contentScriptWhen: "start" to your page-mod options. But you should be aware that at this point there is only the document element present in the DOM, but nothing else, so you need to have your script then wait for other nodes...

Another alternative is that instead of creating <link> elements, you could use the nsIPrefetchService, by having your content-script message-pass a list of links/referrers to your main.js, which would then call the service via require("chrome").

Aside: It might not be the best idea to unconditionally prefetch all links from a bandwidth and performance perspective.

Also aside: Not all links are prefetch-able (mailto: etc).



来源:https://stackoverflow.com/questions/24000598/firefox-add-on-prefetching-with-link-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!