Html link rel preload

Использование технологии preload для ускорения сайтов

Недавно опубликован новый стандарт на технологию Preload (ссылка). Основной задачей этой спецификации было обеспечить возможность тонкого управления логикой загрузки ресурсов страницы разработчиком.

Предыдущие стандарты

Идея об управлении загрузкой не нова. Ранее были разработаны несколько вариантов тегов link с атрибутами subresource, prerender и prefetch. Однако, они работали несколько иначе: с их помощью можно загружать элементы страниц или целые страницы, которые могут потребоваться при дальнейшей навигации по сайту. То есть, браузер отправлял такие запросы с низким приоритетом и в последнюю очередь. Если же нужно повысить приоритет, то решений не было.

Загрузка ресурсов с preload

Что же даёт новая спецификация? Во-первых, теперь загрузка происходит с уточнением, что загружается. Исходя из указанного типа ресурса браузером выставляется приоритет загрузки. Например:

link rel = «preload» href = «/js/script.js» as = «script» >
link rel = «preload» href = «/fonts/1.woff2» as = «font» type = «font/woff2» crossorigin>

Во-вторых, тип ресурса (as) позволяет браузеру послать правильные заголовки, чтобы сервер мог отправить контент с лучшим вариантом сжатия (например, послать WebP картинки, если браузер их поддерживает).

Во втором примере мы загружаем файл шрифта, при этом указан конкретный формат (WOFF2), который поддерживается не всеми браузерами. Однако, пока поддержка механизма preload совпадает с поддержкой такого формата, проблем не возникает. Текущую поддержку механизма можно посмотреть здесь.

Ускоренная загрузка шрифтов

В качестве примера ускорения сайта с использованием preload можно назвать загрузку глубоко закопанных ресурсов, например, шрифтов. В обычном процессе загрузки браузер должен сначала загрузить CSS-файл с указанием на шрифт, провести парсинг этого файла и только потом поставить в очередь запрос на скачивание файла шрифта.

Если мы укажем preload этого шрифта в коде HTML-страницы, браузер отправит запрос сразу же после разбора HTML-документа, что может быть на несколько секунд раньше, чем в обычном случае. А мы знаем, что подключаемые шрифты являются блокирующими элементами и задерживают отрисовку шрифта на странице, поэтому загрузить их нужно как можно быстрее. Особенно остро эта проблема стоит при использовании HTTP/2, когда браузер отправляет сразу множество запросов к серверу, в результате чего какие-нибудь картинки могут заполнить полосу клиента и загрузка важных ресурсов будет отложена.

Асинхронная загрузка CSS

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

Делается это следующим образом:

link rel = «preload» as = «style» href = «async_style.css» onload = «this.rel=’stylesheet'» >

Загрузка JS-кода без исполнения

Также полезным может оказаться предзагрузка кода скрипта на JS, чтобы выполнить его позже.

Это можно сделать с помощью следующего кода:

link rel = «preload» as = «script» href = «async_script.js» onload = «var script = document.createElement(‘script’); script.src = this.href; document.body.appendChild(script);» >

Мы рассмотрели основные способы использования механизма preload, но возможности на этом не ограничиваются, проводите собственные эксперименты!

За профессиональным ускорением сайтов и не только обращайтесь к нам.

Читайте также:  Shadows on sides css

Ускорение сайтов

Экспертное ускорение сайтов

Ускорение сайтов
Цена от 69 900 Р

Источник

rel=preload

You most commonly use to load a CSS file to style your page with:

link rel="stylesheet" href="styles/main.css" /> 

Here however, we will use a rel value of preload , which turns into a preloader for any resource we want. You will also need to specify:

A simple example might look like this (see our JS and CSS example source, and also live):

head> meta charset="utf-8" /> title>JS and CSS preload exampletitle> link rel="preload" href="style.css" as="style" /> link rel="preload" href="main.js" as="script" /> link rel="stylesheet" href="style.css" /> head> body> h1>bouncing ballsh1> canvas>canvas> script src="main.js" defer> script> body> 

Here we preload our CSS and JavaScript files so they will be available as soon as they are required for the rendering of the page later on. This example is trivial, as the browser probably discovers the and elements in the same chunk of HTML as the preloads, but the benefits can be seen much more clearly the later resources are discovered and the larger they are. For example:

  • Resources that are pointed to from inside CSS, like fonts or images.
  • Resources that JavaScript can request, like JSON, imported scripts, or web workers.
  • Larger images and video files.

preload has other advantages too. Using as to specify the type of content to be preloaded allows the browser to:

  • Prioritize resource loading more accurately.
  • Store in the cache for future requests, reusing the resource if appropriate.
  • Apply the correct content security policy to the resource.
  • Set the correct Accept request headers for it.

What types of content can be preloaded?

Many content types can be preloaded. The possible as attribute values are:

Note: font and fetch preloading requires the crossorigin attribute to be set; see CORS-enabled fetches below.

Note: There’s more detail about these values and the web features they expect to be consumed by in the Preload spec — see link element extensions. Also note that the full list of values the as attribute can take is governed by the Fetch spec — see request destinations.

Including a MIME type

elements can accept a type attribute, which contains the MIME type of the resource the element points to. This is especially useful when preloading resources — the browser will use the type attribute value to work out if it supports that resource, and will only download it if so, ignoring it if not.

You can see an example of this in our video example (see the full source code, and also the live version), a code snippet from which is shown below. This illustrates the core behavior behind preloading in general.

head> meta charset="utf-8" /> title>Video preload exampletitle> link rel="preload" href="sintel-short.mp4" as="video" type="video/mp4" /> head> body> video controls> source src="sintel-short.mp4" type="video/mp4" /> source src="sintel-short.webm" type="video/webm" /> p> Your browser doesn't support HTML video. Here is a a href="sintel-short.mp4">link to the videoa> instead. p> video> body> 

The code in the example above causes the video/mp4 video to be preloaded only in supporting browsers — and for users who have video/mp4 support in their browsers, causes the video/mp4 video to actually be used (since it’s the first specified). That makes the video player hopefully smoother/more responsive for users who have video/mp4 support in their browsers.

Note that for users whose browsers have both video/mp4 and video/webm support, if in that code a element were also specified, then both the video/mp4 and video/webm videos would be preloaded — even though only one of them would actually be used.

Therefore, specifying preloading for multiple types of the same resource is discouraged. Instead, the best practice is to specify preloading only for the type the majority of your users are likely to actually use. That’s why the code in the example above doesn’t specify preloading for the video/webm video.

However, the lack of preloading doesn’t prevent the video/webm video from actually being used by those who need it: for users whose browsers don’t have video/mp4 support but do have video/webm support, the code in the example above does still cause the video/webm video to be used — but it does so without also causing it to also be preloaded unnecessarily for the majority of other users.

CORS-enabled fetches

As mentioned above, one interesting case where this applies is font files. Because of various reasons, these have to be fetched using anonymous-mode CORS (see Font fetching requirements).

Let’s use this case as an example. You can see the full example source code on GitHub (also see it live):

head> meta charset="utf-8" /> title>Web font exampletitle> link rel="preload" href="fonts/cicle_fina-webfont.woff2" as="font" type="font/woff2" crossorigin /> link rel="preload" href="fonts/zantroke-webfont.woff2" as="font" type="font/woff2" crossorigin /> link href="style.css" rel="stylesheet" /> head> body>body> 

Not only are we providing the MIME type hints in the type attributes, but we are also providing the crossorigin attribute to make sure the preload’s CORS mode matches the eventual font resource request.

Including media

One nice feature of elements is their ability to accept media attributes. These can accept media types or full-blown media queries, allowing you to do responsive preloading!

Let’s look at an example (see it on GitHub — source code, live example):

head> meta charset="utf-8" /> title>Responsive preload exampletitle> link rel="preload" href="bg-image-narrow.png" as="image" media="(max-width: 600px)" /> link rel="preload" href="bg-image-wide.png" as="image" media="(min-width: 601px)" /> link rel="stylesheet" href="main.css" /> head> body> header> h1>My siteh1> header> script> const mediaQueryList = window.matchMedia("(max-width: 600px)"); const header = document.querySelector("header"); if (mediaQueryList.matches)  header.style.backgroundImage = "url(bg-image-narrow.png)"; > else  header.style.backgroundImage = "url(bg-image-wide.png)"; > script> body> 

We include media attributes on our elements so that a narrow image is preloaded if the user has a narrow viewport, and a wider image is loaded if they have a wide viewport. We use Window.matchMedia / MediaQueryList to do this (see Testing media queries for more).

This makes it much more likely that the font will be available for the page render, cutting down on FOUT (flash of unstyled text).

This doesn’t have to be limited to images, or even files of the same type — think big! You could perhaps preload and display a simple SVG diagram if the user is on a narrow screen where bandwidth and CPU is potentially more limited, or preload a complex chunk of JavaScript then use it to render an interactive 3D model if the user’s resources are more plentiful.

Scripting and preloads

Another nice thing about these preloads is that you can execute them with script. For example, here we create a HTMLLinkElement instance, then attach it to the DOM:

const preloadLink = document.createElement("link"); preloadLink.href = "myscript.js"; preloadLink.rel = "preload"; preloadLink.as = "script"; document.head.appendChild(preloadLink); 

This means that the browser will preload the myscript.js file, but not actually use it yet. To use it, you could do this:

const preloadedScript = document.createElement("script"); preloadedScript.src = "myscript.js"; document.body.appendChild(preloadedScript); 

This is useful when you want to preload a script, but then defer execution until exactly when you need it.

Other resource preloading mechanisms

Other preloading features exist, but none are quite as fit for purpose as :

  • has been supported in browsers for a long time, but it is intended for prefetching resources that will be used in the next navigation/page load (e.g. when you go to the next page). This is fine, but isn’t useful for the current page! In addition, browsers will give prefetch resources a lower priority than preload ones — the current page is more important than the next. See prefetch for more details.
  • renders a specified webpage in the background, speeding up its load if the user navigates to it. Because of the potential to waste users’ bandwidth, Chrome treats prerender as a NoState prefetch instead.
  • Non-standard was supported in Chrome a while ago, and was intended to tackle the same issue as preload , but it had a problem: there was no way to work out a priority for the items ( as didn’t exist back then), so they all got fetched with fairly low priority.
  • There are a number of script-based resource loaders out there, but they don’t have any power over the browser’s fetch prioritization queue, and are subject to much the same performance problems.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

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

Your blueprint for a better internet.

Источник

Оцените статью