JavaScript

Viewport und Lazy Loading - Vanilla JS

Nur laden wenn es wirklich benötigt wird.

Inhalte nur zu laden wenn sie wirklich benötigt werden, sorgt nicht nur dafür dass die Seite schneller das Dom-Ready erreicht, was nicht nur Google erfreut, sondern auch den Betrachter der Website.

Diese Implementierung bringt eine Filterung aller Bilder auf der Seite mit sich, die im data-src-Attribut einen Inhalt entalten, dieser Wert braucht nur in das src-Attribut verschoben werden sobald das Bild im Sichtbaren Bereich auftaucht und auch wirklich sichtbar sein soll.

Einzige Voraussetzung <img data-src="..." />

Diese Variante nutzt den IntersectionObserver und ist die kompakteste Variante die mir bekannt ist, sie hat den Nachteil das sie nicht von allen Browsern (IE11) unterstützt wird.

viewport.js JavaScript (788 bytes) 01.04.2020 00:44
// coding: utf-8
/** Created by: Udo Schmal | https://www.gocher.me/ */
// load image by copy data-src to src, on element moving into viewport the fist time
(function() {
  'use strict';
  // get all images with data-src
  var els = document.querySelectorAll('img[data-src]');
  // create intersection observer
  var observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      if (entry.intersectionRatio > 0) {
        // lazy loading image
        entry.target.setAttribute('src', entry.target.getAttribute('data-src'));
        observer.unobserve(entry.target);
      }
    });
  },
  {
    threshold: [0.1],
    // Set a minimum delay between notifications
    delay: 100
  });
  // start observing
  els.forEach(el => {
    observer.observe(el);
  });
})();

Diese Variante wird auch vom IE11 unterstützt, ist allerdings wesentlich umfangreicher.

viewport_1.js JavaScript (3,13 kByte) 29.02.2020 19:27
// coding: utf-8
/** Created by: Udo Schmal | https://www.gocher.me/ */
(function() {
  'use strict';
  // lazy loading image / iframe
  function loadSrc(el) {
    el.setAttribute('src', el.getAttribute('data-src'));
  }
  // lazy preloading video
  function preloadVideo(el) {
    el.setAttribute('preload', 'auto');
  }
  // Viewport prototype to trigger event if element moves into viewport the fist time
  function Viewport(el, callback) {
    this.el = el;
    // frame must have position attribute for getBoundingClientRect
    if (!this.el.parentNode.style.position) {
      this.el.parentNode.style.position = 'relative';
    }
    this.callback = callback;
    this.observer = null;
    var self = this;
    this.handleEvent.bind(this);
    // is already in viewport
    if (!this.handleEvent('load')) {
      // add event listener to scroll event to check visibility change
      window.addEventListener('scroll', this);
      // create mutation observer if one of the parent node is hidden
      var node = el;
      while(node && node.tagName.toLowerCase() !== 'body') {
        if (node.style.display === 'none') {
          this.observer = new MutationObserver(function(mutations) {
            if (mutations[0].target.style.display !== 'none') {
              self.handleEvent('observer');
            }
          });
          this.observer.observe(node, { attributes: true });
          break;
        }
        node = node.parentNode;
      }
    }
  }

  Viewport.prototype = {
    // check if element is visible
    isVisible: function () {
      var style = window.getComputedStyle(this.el);
      return !!(this.el.offsetWidth || this.el.offsetHeight || this.el.getClientRects().length);
    },
    // check if element is in viewport
    isInViewport: function () {
      var bounding = this.el.getBoundingClientRect();
      return (
        bounding.top >= 0 &&
        bounding.left >= 0 &&
        bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
      );
    },
    // handle the visibility check and the resulting action
    handleEvent: function (e) {
      if (e === 'load' || e === 'observer' || e.type === 'scroll') {
        if (this.isInViewport() && this.isVisible()) {
          this.callback(this.el);
          if (e !== 'load') {
            if (this.observer) {
              this.observer.disconnect();
            }
            window.removeEventListener('scroll', this);
          }
          return true;
        }
      }
      return false;
    }
  };

  // get all images with data-src
  var i, els = document.getElementsByTagName('img'), len = els.length;
  // activate viewport for image loading
  for (i = 0; i < len; i++) {
    if (els[i].hasAttribute('data-src') && els[i].getAttribute('data-src') != '') {
      new Viewport(els[i], loadSrc);
    }
  }
  // activate viewport for video preloading
  els = document.getElementsByTagName('video');
  len = els.length;
  for (i = 0; i < len; i++) {
    if (els[i].hasAttribute('data-src') && els[i].getAttribute('data-src') != '') {
      new Viewport(els[i], loadSrc);
    }
  }
})();

Author: , published: , last modified:

Kontakt

Copyright / License of sources

Copyright (c) 2007-2020, Udo Schmal <udo.schmal@t-online.de>

Permission to use, copy, modify, and/or distribute the software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Service Infos

CMS Info Product Name:
UDOs Webserver
Version:
0.4.2.48
Description:
All in one Webserver
Copyright:
Udo Schmal
Compilation:
Fri, 27. Mar 2020 15:21:45
Development Info Compiler:
Free Pascal FPC 3.3.1
compiled for:
OS:Linux, CPU:x86_64
System Info OS:
Ubuntu 18.04.4 LTS bionic
Hardware Info Model:
Hewlett-Packard HP Pavilion dm4 Notebook PC
CPU Name:
Intel(R) Core(TM) i5-2430M CPU @ 2.40GHz
CPU Type:
x86_64, 1 physical CPU(s), 2 Core(s), 4 logical CPU(s), 2594.147 MHz