What's the right method to set a new prerender or prefetch in HTML?

戏子无情 提交于 2019-12-03 06:48:59
rstackhouse

<link rel="prefetch"> is actually part of the HTML 5 spec.

<link rel="prerender"> appears to be Google doing their own thing.

Justin is incorrect. You do need both prefetch and prerender (or at least a polyfill that will output both) as FF supports prefetch and Chrome supports prerender.

First of all, you confused me a little with the mixing between prefetch & prerender usages. Their usages should be like this:

prefetch usage:

It should be used for fetching and caching resources for later user navigation as per the official HTML5 spec (i.e. prefetching a css file to be used in a page which highly likely to be used by the user in his upcoming navigation). Supported in Chrome, Firefox & IE.

prerender usage:

It should be used for prerendering a complete page that the user will highly likely navigate to it in his upcoming navigation (i.e. like prerendering the next article where it is highly likely that the user will click on "next article" button). Supported only in Chrome & IE.


Back to your question, you can add browser hints (i.e. like the two link you used) as many as you really need, just don't misuse them because they are resource-heavy.

So, you can inject your hints when the page is generated (like what you did), or you can inject them at runtime using javascript like this:

var hint = document.createElement("link");
hint.setAttribute("rel", "prerender");
hint.setAttribute("href", "https://www.apple.com/ipad");

document.getElementsByTagName("head")[0].appendChild(hint);

For a better understanding for what you can do with all "pre-" goodies, see this brilliant presentation by google.

1) You don't need to use both prefetch and prerender links, you only need prerender. A prerender link will load everything prefetch does, and more.

2) To answer your question, use method 2 and insert another prerender link with javascript. Something link this:

<script>
var myHead = document.getElementsByTagName('head')[0];
var myLink = document.createElement('link');
myLink.setAttribute('rel', 'prerender');
myLink.setAttribute('href', 'http://apple.com/ipad');
myHead.appendChild(myLink);
</script>

Or if you use jQuery:

$("head").append('<link rel="prerender" href="http://apple.com/ipad">');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!