js lazy lazy loading an image page images

Lazy Load is a jQuery plugin written in JavaScript, it can be a long delay in loading the page the pictures in the browser viewing area outside the picture will not be loaded until the user scroll the page to their location. This image pre-loading approach is just the opposite.

In the big picture that contains many pages long delay in loading pictures you can speed up page loading. Browser will be loaded after the visible image is in the ready state, in some cases can help reduce the burden on the server.

Lazy Load inspired by Matt Mlinac produced YUI ImageLoader Toolbox This is the demo page .

How to use?

Lazy Load depends on jQuery . add the following code into the page head area:

1
2
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.lazyload.js" type="text/javascript"></script>

And in the execution of your code by adding the following statement:

1
$("http://www.appelsiini.net/projects/lazyload/img").lazyload();

This area will be delayed under the picture will load.

Set sensitivity

Plug-in provides threshold options, you can set the threshold (the trigger to load the image at the distance) to control the images to load default value is 0 (when the load reaches the border pictures).

1
$("http://www.appelsiini.net/projects/lazyload/img").lazyload({ threshold : 200 });

The threshold set at 200, when the viewable area 200 pixels from the picture, when there began to load the picture (this one the original literal meaning, and I understand the inconsistency, the original: Setting threshold to 200 causes image to load 200 pixels before it is visible.)

Placeholder image

You can also set a placeholder image and define the load event to trigger the action. Then need to set a placeholder image URL address transparent, gray and white 1x1 pixel images have been included in the plug inside.

1
$("img").lazyload({ placeholder : "img/grey.gif" });

Event-triggered load

JQuery event can be any time, such as: click and mouseover. You can also use custom events, such as: sporty and foobar. Default, waits until the user scrolls to the location where the picture window in the gray placeholder image Click the images to load before being blocked, you can do:

1
2
3
4
$("img").lazyload({
        placeholder : "img/grey.gif",
        event : "click"
});

Use of special effects

When the image fully loads, plug-in by default use show() method to map displayed. In fact, you can use any special effects you want to deal with the code below to use FadeIn effect, which is the demo page .

1
2
3
4
$("img").lazyload({
        placeholder : "img/grey.gif",
        effect : "fadeIn"
});

Pictures inside the container

You can plug in a scrollable container with a picture, for example, the DIV element with a scroll bar you have to do is define the container for the jQuery object and passed as a parameter inside the initialization method, which is a horizontal scrolling demo page and vertical scrolling demo page .

CSS code:

1
2
3
4
#container {
        height: 600px;
        overflow: scroll;
}

JavaScript code:

1
2
3
4
$("img").lazyload({
         placeholder : "img/grey.gif",
         container: $("#container")
});

When the picture does not order

Scroll down the page when, Lazy Load will load the pictures for the cycle in the loop detection area in the visual image is by default not visible in the first area to find a picture stop the loop. Picture is considered to flow distribution, the order in the page image and HTML code in the same order, but in some of the layout, this assumption is not valid, but you can failurelimit options to control load behavior.

1
2
3
$("img").lazyload({
        failurelimit : 10
});

Will failurelimit to 10 found that plug-in area 10 picture is not visible until the search stops if you have a layout of wretched, please set this parameter higher.

Lazy Loading Images

Lazy Load Plugin for an incomplete features, but it can also be used to implement lazy loading of images below code to achieve page load before loading the page is loaded after 5 seconds, the picture within the designated area automatically loaded, which is delayed loading the demo page .

1
2
3
4
5
6
7
8
9
$(function() {
        $("img:below-the-fold").lazyload({
                placeholder : "img/grey.gif",
                event : "sporty"
        });
});
$(window).bind("load", function() {
        var timeout = setTimeout(function() {$("img").trigger("sporty")}, 5000);
});
/*
 * Lazy Load - jQuery plugin for lazy loading images
 *
 * Copyright (c) 2007-2009 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://www.appelsiini.net/projects/lazyload
 *
 * Version:  1.5.0
 *
 */
(function($) {

    $.fn.lazyload = function(options) {
        var settings = {
            threshold    : 0,
            failurelimit : 0,
            event        : "scroll",
            effect       : "show",
            container    : window
        };

        if(options) {
            $.extend(settings, options);
        }

        /* Fire one scroll event per scroll. Not one scroll event per image. */
        var elements = this;
        if ("scroll" == settings.event) {
            $(settings.container).bind("scroll", function(event) {

                var counter = 0;
                elements.each(function() {
                    if ($.abovethetop(this, settings) ||
                        $.leftofbegin(this, settings)) {
                            /* Nothing. */
                    } else if (!$.belowthefold(this, settings) &&
                        !$.rightoffold(this, settings)) {
                            $(this).trigger("appear");
                    } else {
                        if (counter++ > settings.failurelimit) {
                            return false;
                        }
                    }
                });
                /* Remove image from array so it is not looped next time. */
                var temp = $.grep(elements, function(element) {
                    return !element.loaded;
                });
                elements = $(temp);
            });
        }

        this.each(function() {
            var self = this;

            /* Save original only if it is not defined in HTML. */
            if (undefined == $(self).attr("original")) {
                $(self).attr("original", $(self).attr("src"));
            }

            if ("scroll" != settings.event ||
                    undefined == $(self).attr("src") ||
                    settings.placeholder == $(self).attr("src") ||
                    ($.abovethetop(self, settings) ||
                     $.leftofbegin(self, settings) ||
                     $.belowthefold(self, settings) ||
                     $.rightoffold(self, settings) )) {

                if (settings.placeholder) {
                    $(self).attr("src", settings.placeholder);
                } else {
                    $(self).removeAttr("src");
                }
                self.loaded = false;
            } else {
                self.loaded = true;
            }

            /* When appear is triggered load original image. */
            $(self).one("appear", function() {
                if (!this.loaded) {
                    $("<img />")
                        .bind("load", function() {
                            $(self)
                                .hide()
                                .attr("src", $(self).attr("original"))
                                [settings.effect](settings.effectspeed);
                            self.loaded = true;
                        })
                        .attr("src", $(self).attr("original"));
                };
            });

            /* When wanted event is triggered load original image */
            /* by triggering appear.                              */
            if ("scroll" != settings.event) {
                $(self).bind(settings.event, function(event) {
                    if (!self.loaded) {
                        $(self).trigger("appear");
                    }
                });
            }
        });

        /* Force initial check if images should appear. */
        $(settings.container).trigger(settings.event);

        return this;

    };

    /* Convenience methods in jQuery namespace.           */
    /* Use as  $.belowthefold(element, {threshold : 100, container : window}) */

    $.belowthefold = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return fold <= $(element).offset().top - settings.threshold;
    };

    $.rightoffold = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).width() + $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left + $(settings.container).width();
        }
        return fold <= $(element).offset().left - settings.threshold;
    };

    $.abovethetop = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top;
        }
        return fold >= $(element).offset().top + settings.threshold  + $(element).height();
    };

    $.leftofbegin = function(element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left;
        }
        return fold >= $(element).offset().left + settings.threshold + $(element).width();
    };
    /* Custom selectors for your convenience.   */
    /* Use as $("img:below-the-fold").something() */

    $.extend($.expr[':'], {
        "below-the-fold" : "$.belowthefold(a, {threshold : 0, container: window})",
        "above-the-fold" : "!$.belowthefold(a, {threshold : 0, container: window})",
        "right-of-fold"  : "$.rightoffold(a, {threshold : 0, container: window})",
        "left-of-fold"   : "!$.rightoffold(a, {threshold : 0, container: window})"
    });

})(jQuery);

Download the plug-in

Latest Version: source code , code compression , code package

分类:Internet 时间:2010-11-11 人气:208
分享到:
blog comments powered by Disqus

相关文章

  • javascript原生和jquery库实现iframe自适应高度和宽度 2014-06-02

    这篇文章主要介绍了javascript原生和jquery库实现iframe自适应内容高度和宽度,需要的朋友可以参考下 javascript原生和jquery库实现iframe自适应内容高度和宽度---推荐使用jQuery的代码! ‍<iframe src="index.php" id="mainiframe" name="mainiframe" width="100%" frameborder="0" scrolling="no" marginwidth="0" marginheight=

  • 在JavaScript中重写jQuery对象的方法实例教程 2015-01-01

    这篇文章主要介绍了在JavaScript中重写jQuery对象的方法,在某些情况下jQuery无法满足应用开发的时候可以采用javascript重写jQuery方法来满足功能的实现,需要的朋友可以参考下 jQuery是一个款非常优秀的类库,它给我们解决了很多的客户端编程,但是任何东西都不是万能的,当它不能满足我们的需求时我们就需要对它进行重写,同时也不要影响其原有的功能或者修改其原有的功能;比如我现在的web应用程序大多数时候的数据交互都是通过Ajax来完成的,这样就可以将一些隐藏字段的数据保存

  • Send a html + javascript tool to do: party statement of copyright protected content dog link address Analyzer 2011-01-09

    Can be used on the line. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> Dog statement copyright-protected content Link Analyzer </TITLE> <META NAME="Generator" CONTENT="EditPlus"

  • rman shell script regular clean-up task execution logs oracle 2010-10-27

    Timing the script: cleanarclog.sh #! / Bin / bash oracle_sid = mdspdb oracle_home = "/ opt/oracle/product/11g/db" ps-ef | grep oracle | grep-w "ora_lgwr_ $ {oracle_sid}"> & / dev / null if [$?-ne 0] then exit 0 fi source $

  • javascript in the for .. in statement, and the use of labels 2010-04-18

    for ... in statement is strictly iterative statements, mainly for enumeration object. This is the Object class needs to be said about a property: PropertyIsEnumerable determine whether this property can be used for ... in for enumeration And then exp ...

  • 26 JQuery use of small tips (jQuery tips, tricks & solutions) 2008-07-20

    The use of the jQuery Library is growing and growing (just released jQuery 1.4), more and more people are using this useful JavaScript Library. This means that more and more useful jQuery Tips, tricks and Solutions are coming available. That's why i C

  • Use google jsapi fast loading jquery library (dynamically increase the input and value) 2008-05-09

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title> New Document </title> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascri

  • jQuery implementation of import and navigation bar 2010-05-04

    jQuery is a lightweight JavaScript library. http://jquery.com . The selector has a strong, excellent DOM operation, reliable event handling, excellent compatibility and chain operation functions. jQuery With its simple syntax and cross-platform compatibil

  • Struts2 + JQuery + Json and JQuery examples of related plug-ins 2010-08-03

    Source: http://www.360doc.com/content/10/0731/19/117897_42788515.shtml # Note: 1. Development, should work and the corresponding code page database, located as: utf8 to solve garbage problem; 2. The current development version struts2.1.8, different versi

  • Jquery use in blockUI 2010-11-30

    Jsp the information: <body> Test Show Block Information.<input type="button" value="show Block information" /><br> </body> JavaScript information: <script type="text/javascript" src="js/jquery-1.2.3.js"></script>

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.224 (s). 12 q(s)