Preload

Using rel=preload for responsive images

Doesn’t HTTP/2 Push Cover Those Same Use Cases?

Not really. While there is some overlap between the features, for the most part, they complement each other.

HTTP/2 Push has the advantage of being able to push resources that the browser hasn’t sent the request for yet. That means that Push can send down resources before the HTML even started to be sent to the browser. It can also be used to send resources down on an open HTTP/2 connection without requiring a response on which HTTP Link headers can be attached.

On the other hand, preload can be used to resolve use cases that HTTP/2 cannot. As we’ve seen, with preload the application is aware of the resource loading taking place, and can be notified once the resource was fully loaded. That’s not something HTTP/2 Push was designed to do. Furthermore, HTTP/2 Push cannot be used for third-party resources, while preload can be used for them just as efficiently as it would be used on first-party resources.

Also, HTTP/2 Push cannot take the browser’s cache and non-global cookie state into account. While the cache state might be resolved with the new cache digest specification, for non-global cookies there’s nothing that can be done, so Push cannot be used for resources that rely on such cookies. For such resources, preload is your friend.

Another point in preload’s favor is that it can perform content negotiation, while HTTP/2 Push cannot. That means that if you want to use Client-Hints to figure out the right image to send to the browser, or headers in order to figure out the best format, HTTP/2 Push cannot help you.

What about the element

But how does this work for the element where you’re specifying different images based on a media query. For this we simple modify the original rel=”preload” reference. But first, here’s an example image…

In this instance we need only add the attribute and duplicate the reference for each image size.

The main difference between this and the media attributes within the image is that you need to specify both min and max widths for those in-between images. Unlike the element the browser isn’t going to load only a single image based on what best fits the current screen size. In the case of preload, the browser will load anything that meets the criteria set within the media attribute, even if that means loading images that won’t be output to the page.

Use with a Font Loading Strategy #

isn’t a panacea because it’s not sufficient by itself as a font loading strategy. There are two major considerations to font loading: (1) Eliminating the Flash of Invisible Text (FOIT) by showing a Flash of Unstyled Text (FOUT) and (2) Speeding up font loading to minimize the amount of time that fallback text is shown. We want to reduce the jarring reflows that happen when content is re-rendered with our new, shiny web fonts. An ideal strategy would eliminate both FOIT and FOUT.

helps our second point but does nothing for the first. We still need to implement a FOUT strategy—of course, my favorite is still Critical FOFT with an inline Data URI for the first stage. This strategy has shown to eliminate FOIT and FOUT, but at a cost documented above (and in the Data URI post). Let’s see how plays out there:

(Times generated using Chrome Canary’s Developer Tools Network Throttling in Regular 3G mode)

2-Stage Font Loading Strategies
Critical FOFT Critical FOFT Roman Data URI Critical FOFT
Initial Render 588ms   58.6KB HTML 619ms (+5%) 65.7KB HTML 675ms (+14%) 58.6KB HTML
Stage 1 Render (Critical Roman) 1.04s 619ms (-40%) 675ms (-35%)
Stage 2 Render (Roman, Italic, Bold, Bold Italic) 2.57s 2.44s (-5%) 2.29s (-10%)

The results are pretty good for a Two Stage font loading approach. If your web font requirements are a little simpler and you’re only loading a single web font (One Stage font loading), then will have a similar beneficial performance gain. However, if you’re loading multiple web fonts in a grouped load (again, One Stage) with a single repaint/reflow step, isn’t wise: if you one of the fonts, the repaint/reflow will not happen until all web fonts have completed and it will be wasted; if you all of them, the sacrifices to initial render are too costly.

How To Implement the Audio Tag?

The HTML audio tag is used to play any audio file on your web page, and because of this, it is also known as the HTML music player. To add music in HTML documents, you should use the HTML audio element with both an opening and a closing tag. Since there are several elements you are supposed to use for correct syntax, take a closer look at the following list to learn something more:

  • The HTML audio element – used only as a player for the audio document
  • The HTML source element – used to introduce and specify the alternative audio files
  • Specific HTML attributes – used to improve and help your browser correctly render the audio file

Web developers should use all these elements and attributes for a single HTML play sound. It is also worth noting that a single HTML play audio element may contain multiple HTML source elements. They are always nested inside the opening and closing audio tags, where the element’s content is also located. Now, let us learn how to create the syntax by reading the following section of this article.

Didn’t We Already Have That?

Kinda, but not really. has been supported on the web for a long while, and has . On top of that we’ve also supported in Chrome for some time. So what’s new about preload? How is it different from these other directives? They all tell the browser to fetch things, right?

Well, they do, but there are significant differences between them. Differences that warrant a shiny new directive that tackles many use cases that the old ones never did.

is a directive that tells a browser to fetch a resource that will probably be needed for the next navigation. That mostly means that the resource will be fetched with extremely low priority (since everything the browser knows is needed in the current page is more important than a resource that we guess might be needed in the next one). That means that prefetch’s main use case is speeding up the next navigation rather than the current one.

was originally planned to tackle the current navigation, but it failed to do that in some spectacular ways. Since the web developer had no way to define what the priority of the resource should be, the browser (just Chrome and Chromium-based browsers, really) downloaded it with fairly low priority, which meant that in most cases, the resource request came out at about the same time that it would if subresource wasn’t there at all.

Final Words and Additional Notes:

The HTML audio element is used to insert and play a specific audio file on your web page. A lot of important points and details were covered in this article, and they are all summarized in the following bullet list:

  • It is possible to nest this HTML element inside other elements in the document
  • The HTML source attribute is usually nested inside the opening and closing HTML audio tags
  • You are supposed to include the attributes for the audio element inside the opening tag
  • The most common attribute is the HTML controls that introduces the user interface
  • It is possible to create a fully-functional HTML audio syntax without the source element

Working with various HTML elements and attributes may sometimes be a challenge, but this is not the case with the HTML audio tag. This article made you an expert, and you do not have to worry about making a mistake once including it in your HTML document.

Last Thoughts on “link rel=preload” for Key Requests and Holistic SEO

Preload is a resource loading hint (browser hint) to provide insights to a browser for loading a web page accurately for a better user experience. “link rel=preload” for key requests from critical request chain, and its attributes such as “as”, or “crossorigin” can help an SEO and Developer to improve the crawl ability, quality score, and usability of the web page for users, and search engine crawlers. Using, preload resource load hint with a wrong methodology, or with a less effective method can cause crawling efficiency problems, along with preventing search engines’ to see a web page’s styled version. To improve the rendering cost, and user-centric page speed metrics, along with the crawlability, using resource load hints such as preload is a must for an SEO Project. Resource Load Order Optimization should be a stage for the Technical SEO and Web Development intersection. And, Holistic SEOs who want to improve their skills for every vertical of SEO should be aware of usage tips for preload, and the nature of browsers for rendering a web page, for instance, critical request change, DOM-tree, CSSOM, or crossorigin attribute.

The “link rel=preload” guideline will be updated in light of new information.

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 resources a lower priority than ones — the current page is more important than the next. See Link prefetching FAQ 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 as a NoState prefetch instead.
  • was supported in Chrome a while ago, and was intended to tackle the same issue as , but it had a problem: there was no way to work out a priority for the items ( 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.

Differences between preload and prefetch

Besides , there is another directive called which shares some faint similarities with . However, both differ in how and when the resource is fetch by the user agent.

Prefetching enables the browser to begin fetching (in the background) resources needed to render a particular page which the user is likely to access next. These fetched resources are then stored in the browser’s local cache and delivered to the user from cache upon accessing the page in question.

The main difference between both directives is that prefetch aims to fetch resources for the next navigation which are low priority. however, focusses on the current navigation and fetches resources with high priority. Each method performs a different task. However, they both share the common goal of helping to improve page load speeds by methods that set out to efficiently perform additional tasks in the background.

Including media

One nice feature of elements is their ability to accept attributes. These can accept 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 example</title>

  <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 site</h1>
  </header>

  <script>
    var mediaQueryList = window.matchMedia("(max-width: 600px)");
    var 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 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 / 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.

preload web pages examples

The following section runs through a few examples of how the directive can be used in web page configurations.

Example 1

The first example demonstrates a simple use case for preloading style sheet. This can be achieved either by using a element or via JavaScript. This is useful when a resource is being called via CSS or JavaScript, however, you would like to have it load immediately. Without the directive, a browser’s preloader may not take these resources into account until it is late in the loading process.

Example 2

According to the , when preloading fonts there is an additional attribute which must be taken into consideration.

This holds true even if the fonts are loaded from your current domain.

Example 3

In order to download a particular resource that you know you’ll need in the future but want to define when exactly it should be executed, the following snippets can be used. The snippet below will preload the resource, which can be defined at the top of the page.

This will therefore allow the script to download in the background. Once you have determined when you want to run the preloaded script, simply add the following snippet which will execute the JS file. When implemented correctly, this can help improve the critical path as scripts can be executed when there are no other critical resources that need to be loaded.

Example 4

Through the use of link tags which can be used as HTTP headers, you can define a header to perform a action. This can be useful when the person who is editing markup is different from the person doing optimization. The following snippet is an example of how setting an HTTP response header may look like:

What are the Basics of Preload?

The basics of preload involve the syntax of preload and attributes related to using it. The basics of preload and related attributes are listed below.

  • “href” attribute for specifying the resource that will be preloaded
  • “as” attribute to specify the type of the resource

The as attribute is to provide the type of the preloaded resource. The type of information will help the browser to prioritize the resource with better precision and cache it within the browser cache. The values that can be used for the “as” attribute are “script”, “font”, “image”, “style”, “object”, “worker” and others. Example usage of the “href” and “as” attributes with the “preload” is below.

In the example above, the preloaded resources which are “style.css”, and “main.js” are called separately with the “script” and “link” tags after the “preload” link elements. Because, the preloaded resource can be fetched and downloaded earlier, but to use it earlier, the browser will need a second declaration by specifying its type within the attribute “as”. At the second call with the related type information of the preloaded resource, the browser won’t download the resource a second time, but it will use it directly with high priority. Thus, preloading and declaring the same resource with the related type are connected to each other for prioritizing the usage of the related resource.

What is Cache Preloaded?

Preloaded resources of a web page have a place within the HTTP Cache Hierarchy. A resource that is cached with the “preload” will be kept in the “session-based” cache of the browser. When the session is stopped, the preload cache will be purged. Since the preloaded resources are a high priority, most of the time they are used also for other web pages of the same website. In this context, a preloaded resource can be cached to eliminate extra requests, downloading and compiling for the next web pages. To use the “preload cache”, the “as” attribute should be used with the correct format. If the “as” attribute is omitted, or if the value for the “as” attribute is wrong, browser will handle the preloaded request as an XHR request. And, the browser won’t be able to prioritize the preloaded resource correctly. In the same context, the “crossorigin” attribute should be used with preload browser command for the font files. If the “crossorigin” is not used, the specific font file will be requested two times. To cache the font files in a correct format with preload cache, the “crossorigin” attribute will provide the correct insights for the browser.

To understand the HTTP Cache Hierarchy along with cache preloaded, the guidelines below are related.

  • Last Modified Response Header
  • Expires Response Header
  • eTag Response Header
  • Cache-control Response Header

Why shouldn’t the onLoad event be used with “link rel=preload”?

There are two main reasons for not using the JavaScript “onLoad” event with “link rel=preload”.

  • Better Performance: onLoad event is a JavaScript-based trigger to make a conditional request happen during the early stage of the lifecycle of a web page. Using onLoad event with “link rel=preload” can cause a browser to use JavaScript rendering to give the basic styles of a web page. In other words, without rendering the JavaScript, giving the styles of a web page wouldn’t be possible. In this context, the first thing a browser does to render a web page is to complete the Document Object Model, and then the Cascaded Style Sheet Object Model. Together, the DOM and the CSSOM create the “Rendering Tree” for the web page. If a browser needs to render JavaScript to complete the Rendering Tree, it will cause extra cost in terms of time since it changes the natural order of the creation of a web page from the point of view of a modern browser.
  • Clarity for Search Engines: The second possible harm of “onLoad JavaScript event with preload” is to hide the content from Search Engine Crawlers if they do not render the JavaScript during their crawling hits. Since Google and Microsoft Bing Search Engines do not render JavaScript 100% for every time they crawl a web page, hiding the style of a web page behind the JS Rendering can affect the crawlers of search engines’ perception of the specific website, and it can cause continuous processes of re-ranking with high velocity. Since, the search engine is not sure whether the JS-rendered content exists within the web page, or not, they can’t have a high confidence score to provide the styles’ effect for the specififc web page’s evaluation, and association processes for quality assignment.

Understanding the effects of “onLoad Event” for a web page, and its connection to the Rendering Tree requires knowing the things below.

  • What is JavaScript?
  • What is HTML?
  • What is CSS?

What are resource hints?

”preconnect”, “dns-prefetch”, and “preload” are all relationship types of resource links — the  “rel” attribute in a link tag. According to the W3C, a resource hint link uses one of these relationships to indicate an origin or resource that should be connected to, or fetched, by the user agent. That’s a pretty vague description, so let’s break that down a bit further.

Fetch

What must happen in order to connect to a resource? For resources on other domains, or cross-origin resources, we can get a good sense of the steps involved by referring to the Network requests in Chrome Dev Tools. 

When selecting a resource on another domain (in this case gtm.js from googletagmanager.com) and reviewing the Timing tab, you can see the Connection Start requires a DNS lookup, initial connection, and SSL. These actions happen in that order as the DNS lookup, TCP handshake, and SSL/TSL handshake. After the connection has been established, the browser/client can send a request to the server and receive a response, which is indicated in the Request/Response timings..

Origin vs Resource

When thinking about these relationships, we must consider what we’re connecting to. Origin refers to the scheme, hostname, and port of a URL, so it’s referring specifically to connecting to other domains. “preconnect” and “dns-prefetch” are used for connecting to other origins, which is why those are listed in the “preconnect to required origins” guide from Google. However, at the end of that guide it is recommended that we use “preload” in most cases. “preload” is able to do more than just establish early connections with domains. Let’s look a little deeper into what each type does.

DNS-Prefetch

Somewhat self-explanatory, “dns-prefetch” helps resolve domain names before the resource is requested. Therefore, this type will start the DNS lookup portion of the connection before the time of the request.

“dns-prefetch” is not supported on Opera Mini, and is not supported via HTTPS on Firefox. If your site is using HTTPS (as it should be), then you will need another option for Firefox users.


Source: https://caniuse.com/link-rel-dns-prefetch

Preconnect

“preconnect” has the browser handle all of the DNS lookup, TCP handshake, and TLS handshake (all of the Connection Start timings) before the request to the server.

Unfortunately, “preconnect” is supported on even fewer browsers than “dns-prefetch.”


Source: https://caniuse.com/link-rel-preconnect

Preload

The “preload” relationship type is the one recommended by Google in most cases, because it is the most comprehensive. This resource hint tells the browser to prioritize downloading and then caching the resource to have ready at the time of the request.

In order to use “preload,” you must know the type of resource you are requesting and add an additional attribute of “as” to the link tag. and know that some browsers limit the types of content that can be preloaded, while many browsers simply do not support “preload” at all.


Source: https://caniuse.com/link-rel-preload

What are the relevant concepts for browser hints like Preload?

To understand the working principle of the “preload” browser hint at the working principles of the things below should be understood.

  • Web Browser
  • Web Server
  • User-agent
  • Website
  • Web page

A web browser sends the resources to the web browser when a user agent requests them from the webserver. A website and a web page can be loaded via a web browser with different resource loading prioritization. A web browser might not support a web browser loading hint or feature, thus the web browser’s version and the type are important. Preload web browser resource prioritization hint is relevant to the nature of browser, server, website, webpage, and user-agent concepts’ relations to each other.

C. Privacy and Security

This section is non-normative.

Preload is a declarative fetch primitive that initiates early fetch of
resources and separates fetching from resource execution. In effect, it is
conceptually similar to initiating a scripted fetch for a resource, but
with additional constraints and benefits:

  • The resource declaration is visible via HTTP headers or HTML markup,
    which allows the user agent to initiate the fetch earlier, and without
    blocking on JavaScript execution.
  • The response is not executed and there is no callback to retrieve its
    payload. The response is retrieved and executed by initiating another
    fetch (via script, DOM element, etc) that matches the preloaded
    response.
  • The developer can specify the target context that will consume the
    response via attribute, which allows the user agent to enforce the
    relevant CSP policies when initiating the preload fetch. If is
    omitted, preload defaults to same security and privacy processing as a
    call to — i.e. subject to .

Step 2 — Preloading Resources

To prevent the default render-blocking and to make sure that page resources like fonts and CSS start loading early in the page life cycle, you will need to implement preloading. The attribute value is used to preload assets. It can be applied to several file formats, including CSS, JS, fonts, images, and more. Depending on the type of file you would like to preload, the corresponding attribute may also need to be included along with . For CSS, will need to be set equal to . For JavaScript, will need to be set equal to .

Return to the HTML file and change the previous . Set equal to . Add the attribute set equal to :

index.html

With your HTML file opened in Google Chrome, return to Developer Tools and load the page with Network still set to Slow 3G. You’ll see that the log shows up right before the CSS request starts, as the following image shows:

However, you may have noticed that the CSS style hasn’t been applied to the text. That’s because using preload or prefetch only fetches the resource, but it doesn’t apply it. Instead, preload and prefetch will keep the resource in memory. You have to define when the resource will be loaded.

The font needs to be applied as soon as it loads. To make this happen, add the attribute to the tag. Set equal to :

index.html

By setting the attribute to in , the browser is told to use the resource. Since it’s been already downloaded in memory, it doesn’t download it again.

Since the solution relies on JavaScript, add tags which contain the original tags with set to :

index.html

This will ensure that the font displays if JavaScript is disabled or fails to load.

You now know how to preload your web page assets. There are times when you may want to prefetch your resources instead.

Понравилась статья? Поделиться с друзьями:
Setup Pro
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: