JavaScript實現圖片的延遲載入

banq發表於2010-11-11
JavaScript Lazy image loading | The Matthias Chronicles

無需Jquery等庫:

<script type="text/javascript">
function AddWindowEvent(elm, evType, fn, useCapture)
  {
    if(elm.addEventListener)
      {
        elm.addEventListener(evType, fn, useCapture);
        return true;
      }
    else if (elm.attachEvent)
      {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
      }
    else
      {
        elm['on' + evType] = fn;
        return(true);
      }
    return(false);
  }

function InitializeLazyLoading()
  {
     AddWindowEvent(window,'scroll',LazyLoadImage,false);
     LazyLoadImage();
  }

function IsViewPort(e)
  {
    var mx=0, my=0, tx=0, ty=0;
    var scrOfX=0, scrOfY=0;

    if(typeof(window.innerWidth) == 'number')
      {
        mx = window.innerWidth;
        my = window.innerHeight;
      }
      else  // Below is single line
    if(document.documentElement && 
      (document.documentElement.clientWidth || 
       document.documentElement.clientHeight))
      {
        mx = document.documentElement.clientWidth;
        my = document.documentElement.clientHeight;
      }
    else  // Below is single line
    if(document.body && 
      (document.body.clientWidth || 
       document.body.clientHeight))
      {
        mx = document.body.clientWidth;
        my = document.body.clientHeight;
      }

    if(typeof(window.pageYOffset) == 'number')
      {
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
      }
    else  // Below is single line 
    if(document.body && 
      (document.body.scrollLeft || 
       document.body.scrollTop))
      {
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
      }
    else  // Below is single line
    if(document.documentElement && 
      (document.documentElement.scrollLeft || 
      document.documentElement.scrollTop))
      {
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
      }

    tx=mx+scrOfX;
    ty=my+scrOfY;

    // Below is single line
    if(e.offsetLeft>=scrOfX && 
       e.offsetTop>=scrOfY && 
       e.offsetLeft<=tx && 
       e.offsetTop<=ty)
      return true;
    else
      return false;
  }

function LazyLoadImage()
  {
    var Imgs;
    var i;
    var e;

    Imgs=document.getElementsByTagName('img');

    for(i=0; i<Imgs.length; i++)
      {
        e=Imgs[i];

        if(e.src!=e.alt && IsViewPort(e)==true)
          e.src=e.alt;
      }
  }

window.onload=InitializeLazyLoading;
</script>

用法:

<img src="(placeholder image)" alt="real image">
<p class="indent">


相關文章