

If compatibility across browsers is crucial, be sure to read the next section, which shows you how to lazy-load images using less performant (but more compatible!) scroll and resize event handlers. Intersection Observer is not supported in all browsers, notably IE11 and below.

While this approach is the most compatible across browsers, modern browsers offer a more performant and efficient way to do the work of checking element visibility via the Intersection Observer API.
#CSS BACKGROUND IMAGE RESIZE CODE#
If you've written lazy-loading code before, you may have accomplished your task by using event handlers such as scroll or resize. If they are, their src (and sometimes srcset) attributes are populated with URLs to the desired image content. To polyfill lazy-loading of elements, we use JavaScript to check if they're in the viewport.

To learn more, check out Browser-level lazy-loading for the web. If you have large numbers of images and want to be sure that users of browsers without support for lazy-loading benefit you will need to combine this with one of the methods explained next. If the browser does not support lazy-loading then the attribute will be ignored and images will load immediately, as normal.įor most websites, adding this attribute to inline images will be a performance boost and save users loading images that they may not ever scroll to. See the loading field of MDN's browser compatibility table for details of browser support. We suggest not to lazy-load iframes using the loading attribute until it becomes part of the specification. While implemented in Chromium, it does not yet have a specification and is subject to future change when this does happen. A value of lazy tells the browser to load the image immediately if it is in the viewport, and to fetch other images when the user scrolls near them. This attribute can be added to elements, and also to elements. Using scroll and resize event handlers Using browser-level lazy-loading #Ĭhrome and Firefox both support lazy-loading with the loading attribute.With inline images we have three options for lazy-loading, which may be used in combination for the best compatibility across browsers: The most common lazy-loading candidates are images as used in elements. In this post you will find out how to lazy-load both types of image. Images can appear on a webpage due to being inline in the HTML as elements or as CSS background images. Using event handlers for Internet Explorer support.
