Html link rel prefetch

Prefetch

Prefetching refers to the practice of speculatively fetching resources in the background for pages that the user is likely to navigate to in the near future. This can significantly reduce the load time for the prefetched page if the user does choose to navigate to it. Prefetching might be used, for example, to fetch the page resources linked by a «Next» button, or a link popup that a user hovers over, or search results.

Resource prefetching

Resources should be prefetched based on how likely it is that they will be needed in a future navigation. Browsers can infer this automatically for some resources, such as the current URL in the address bar.

Browsers will also prefetch content for elements that have the rel=»prefetch» attribute. This allows developers to hint to the browser the likely navigation from the current page. Note that only these links are prefetched (so elements are not), and that they are fetched at lower priority that resources used by the current page, including elements with fetchPriority=»low» .

Prefetching can be used to fetch both HTML and sub-resources for a possible next navigation. A common use case is to have a simple website landing page that fetches more «heavy-weight» resources used by the rest of the site.

link rel="prefetch" href="/app/style.css" /> link rel="prefetch" href="https://example.com/landing-page" /> 

The fetch request for a prefetch operation results an HTTP Request that includes the HTTP header Sec-Purpose: prefetch , which a server might use to change the cache timeouts for the resources, or perform other special handling. The request should also include the Sec-Fetch-Dest header with the value set to empty . The Accept header in the request should match the value used for normal navigation requests, so that the browser can find the matching cached resources following navigation. If a response is returned, it is cached with the request in the HTTP cache.

Note: Browser vendors are currently aligning around the HTTP headers that are sent, and may use different headers and values. The best place to track specification compliance is the Sec-Purpose compatibility table.

DNS Prefetching

DNS prefetching resolves domain names in advance thereby speeding up load times by reducing the time associated with domain lookup at request time.

link rel="dns-prefetch" href="https://example.com/" /> 

See also

Found a content problem with this page?

This page was last modified on Jul 1, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Ускоряем загрузку ресурсов для сайта: preconnect, prefetch, prerender, preloading…

Стадии загрузки ресурса / HTML5 Link Prefetch

Сегодня мы рассмотрим «HTML5 Link Prefetch», а именно dns-prefetch, prefetch, preconnect, subresource, prerender и еще неработающий preload. HTML5 Link Prefetch уменьшит время загрузки для ресурсов, которые нам понадобятся позже.

Dns-prefetch

Перед тем, как начать загружать сожержимое сайта http://example.com , браузеру нужно установить его IP адрес. И только после этого он сможет загрузить от туда содержимое. Конечно, на это потребуется какое-то время. Если вам нужно что-то загрузить с другого домена, укажите . Браузер преобразует имя домена в IP адрес в фоне. Теперь, когда очередь дойдет до ресурсов, они загрузятся минуя стадию prepresolve. Поддержка браузерами и пример:

 http-equiv="x-dns-prefetch-control" content="on">  rel="dns-prefetch" href="//ajax.googleapis.com"> 
 http-equiv='x-dns-prefetch-control' content='on'>  rel='dns-prefetch' href='http://g-ecx.images-amazon.com'>  rel='dns-prefetch' href='http://z-ecx.images-amazon.com'>  rel='dns-prefetch' href='http://ecx.images-amazon.com'>  rel='dns-prefetch' href='http://completion.amazon.com'>  rel='dns-prefetch' href='http://fls-na.amazon.com'> 

Preconnect

Похоже на dns-prefetch, только круче. Помимо DNS устанавливает TCP, TLS связь. Помогает предгрузить соединение для веб сокетов. Поддержка браузерами и пример:

 rel="preconnect" href="//www.example.com"> 

Prefetch

Указываем браузеру что этот ресурс потребуется нам и браузер загрузит его с низким приоритетом и положит в кэш. Браузер может не загрузить большие файлы при медленном соединении, а Firefox загружает ресурсы только в режиме простоя. Поддержка браузерами и пример:

  rel="prefetch" href="https://ymatuhin.ru">  rel="prefetch" href="https://ymatuhin.ru/img/yury_matuhin.jpg"> 

Subresource

То-же что и prefetch, только с высоким приоритетом. Поэтому я бы рекомендовал добавлять этот атрибут для критических стилей. Поддержка браузерами и пример:

 rel="subresource" href="critical/app.js">  rel="subresource" href="critical/style.css"> 

Prerender

Этот параметр заранее загружает ресурс или страницу и всё её содержимое в фоне. Это как открытие страницы в фоновой вкладке. Браузер загрузит все ресурсы, построит DOM, применит CSS и JS. А когда пользователь перейдет по ссылке, скрытая страница станет заместо текущей и загрузится моментально. В Google поиске давно действует такая штука под названием Instant Pages, Microsoft недавно объявили что они будут использовать prerender в Bing на IE11. Поддержка браузерами и пример:

 rel="prerender" href="https://ymatuhin.ru/index.html"> 

Preloading

Эта штука еще не работает, но её внесли в спецификацию. Работает так-же как и prefetch, но браузер всегда загрузит ресурс. Аналог прелоадеров для картинок, только нативный. Пока он не поддерживается, используйте prefetch. Пример:

Добавление через JavaScript

function add_hint(type, url)  if (!type || !url) return; var el = document.createElement("link"); el.setAttribute("rel", type); el.setAttribute("href", url); document.getElementsByTagName("head")[0].appendChild(el); > add_hind('prefetch', 'http://ya.ru'); 

Дополнительная информация

На этом сайте я использую prefetch для подготовке к загрузке файла, который подсвечивает код, если такой блок находится на странице. Dns-prefetch для ускорения загрузки яндекс метрики. И скрипт, для ускорения переходов между страницами:

document.addEventListener("mousemove", function (e)  if (!e.target.href || e.target.href.indexOf(location.host) == -1 || e.target.hintAdded) return; // функция описана выше add_hint('prerender', e.target.href); e.target.hintAdded = true; >); 

Если браузер не поддерживает HTML5 Link Prefetch, то проигнорирует эти атрибуты, поэтому их можно безопасно использовать.

Cсылки

Еше можно подписаться на email рассылку новых заметок. Не чаще раза в неделю, без спама.

Источник

Читайте также:  Www gas nn ru cab php
Оцените статью