elstretch vs backstretch

Benchmark created by elstretch on


Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Test runner

Ready to run.

Testing in
TestOps/sec
elstretch2
/*
 * jQuery 'onImagesLoaded' plugin v1.1.1 (Updated January 27, 2010)
 * Fires callback functions when images have loaded within a particular selector.
 *
 * Copyright (c) Cirkuit Networks, Inc. (http://www.cirkuit.net), 2008-2010.
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * For documentation and usage, visit "http://includes.cirkuit.net/includes/js/jquery/plugins/onImagesLoad/1.1.1/documentation/"
 */

(function($) {
  $.fn.onImagesLoad = function(options) {
    var self = this;
    self.opts = $.extend({}, $.fn.onImagesLoad.defaults, options);

    self.bindEvents = function($imgs, container, callback) {
      if ($imgs.length === 0) { //no images were in selection. callback based on options
        if (self.opts.callbackIfNoImagesExist && callback) {
          callback(container);
        }
      } else {
        var loadedImages = [];
        if (!$imgs.jquery) {
          $imgs = $($imgs);
        }
        $imgs.each(function(i) {
          //webkit fix inspiration thanks to bmsterling: http://plugins.jquery.com/node/10312
          var orgSrc = this.src;
          if (!$.browser.msie) {
            this.src = ""; //ie will do funky things if this is here (show the image as an X, only show half of the image, etc)
          }
          $(this).bind('load', function() {
            if (jQuery.inArray(i, loadedImages) < 0) { //don't double count images
              loadedImages.push(i); //keep a record of images we've seen
              if (loadedImages.length == $imgs.length) {
                if (callback) {
                  callback.call(container, container);
                }
              }
            }
          });
          if (!$.browser.msie) {
            this.src = orgSrc; //needed for potential cached images
          } else if (this.complete || this.complete === undefined) {
            this.src = orgSrc;
          }
        });
      }
    };

    var imgAry = []; //only used if self.opts.selectorCallback exists
    self.each(function() {
      if (self.opts.itemCallback) {
        var $imgs;
        if (this.tagName == "IMG") {
          $imgs = this;
        } //is an image
        else {
          $imgs = $('img', this);
        } //contains image(s)
        self.bindEvents($imgs, this, self.opts.itemCallback);
      }
      if (self.opts.selectorCallback) {
        if (this.tagName == "IMG") {
          imgAry.push(this);
        } //is an image
        else { //contains image(s)
          $('img', this).each(function() {
            imgAry.push(this);
          });
        }
      }
    });
    if (self.opts.selectorCallback) {
      self.bindEvents(imgAry, this, self.opts.selectorCallback);
    }

    return self.each(function() {}); //dont break the chain
  };

  //DEFAULT OPTIONS
  $.fn.onImagesLoad.defaults = {
    selectorCallback: null,
    //the function to invoke when all images that $(yourSelector) encapsultaes have loaded (invoked only once per selector. see documentation)
    itemCallback: null,
    //the function to invoke when each item that $(yourSelector) encapsultaes has loaded (invoked one or more times depending on selector. see documentation)
    callbackIfNoImagesExist: false //if true, the callbacks will be invoked even if no images exist within $(yourSelector).
    //if false, the callbacks will not be invoked if no images exist within $(yourSelector).
  };
})(jQuery);


(function($) {

  $.fn.elStretch = function(options) {

    options = $.extend({
      imagewidth: 1024,
      imageheight: 768,
      alt: false,
      alttext: "alternative image description",
      fadefirst: false,
      interval: 5000,
      fadingspeed: 1000,
      arrayname: bgimages,
      loadingani: true,
      loadinggif: "img/loading.gif"
    }, options);

    return this.each(function() {

      // VARIABLES FROM OPTIONS, GLOBAL
      var st_originalheight = $(options.imageheight);
      st_originalheight = st_originalheight[0];
      var st_originalwidth = $(options.imagewidth);
      st_originalwidth = st_originalwidth[0];
      var st_interval = $(options.interval);
      st_interval = parseInt(st_interval[0]);
      var st_fadingspeed = $(options.fadingspeed);
      st_fadingspeed = parseInt(st_fadingspeed[0]);
      var st_array = $(options.arrayname);

      // INTERVAL MUST BE HIGHER THAN FADINGSPEED TO PREVENT CONFLICTS
      if (options.interval <= options.fadingspeed) {
        var st_interval = $(options.fadingspeed);
        st_interval = parseInt(st_interval[0]) + 500;
      }

      // GENERAL GLOBAL VARIABLES
      var st_container = $("#elstretch");
      var st_windowwidth = $(this).width();
      var st_windowheight = $(this).height();
      var st_bgcount = st_array.length;
      var st_currentpos = 0;

      function AttachFirstImage() {
        st_container.prepend("<img class='stretch' src='" + st_array[st_currentpos] + "' alt='" + options.alttext + "' style='display: none;' />");
      }

      AttachFirstImage();

      // CHANGE SIZE AND POSITION OF IMAGES

      function ChangeSizesAndPositions() {

        st_windowwidth = $(this).width();
        st_windowheight = $(this).height();
        var windowratio = st_windowwidth / st_windowheight;
        var sourceratio = st_originalwidth / st_originalheight;

        if (sourceratio < 1) {
          // do sth for high images
        } else {
          if (windowratio >= sourceratio) {

            var widthratio = st_windowwidth / st_originalwidth;
            var newheight = st_originalheight * widthratio;
            var newwidth = st_originalwidth * widthratio;
            var topdifference = (st_windowheight - newheight) / 2;
            $("img", st_container).css({
              "width": newwidth,
              "height": newheight,
              "margin-top": topdifference,
              "margin-left": "auto"
            });

          } else {

            var heightratio = st_windowheight / st_originalheight;
            var newheight = st_originalheight * heightratio;
            var newwidth = st_originalwidth * heightratio;
            var leftdifference = (st_windowwidth - newwidth) / 2;
            $("img", st_container).css({
              "width": newwidth,
              "height": newheight,
              "margin-left": leftdifference,
              "margin-top": "auto"
            });
          }
        }
      }


      // CALL FUNCTIONS
      if (options.fadefirst == true) {
        $("img", st_container).fadeIn("slow");
      } else {
        $("img", st_container).show();
      }

      ChangeSizesAndPositions();

      function Fader(st_fadingspeed, st_interval, st_container) {

        function FadeImages() {

          var currentimg = $("img", st_container);
          var ciwidth = $(currentimg).width();
          var ciheight = $(currentimg).height();
          var cileft = $(currentimg).css("margin-left");
          var citop = $(currentimg).css("margin-top");

          console.log("st_currentpos (before): " + st_currentpos);

          if (st_currentpos == (st_bgcount - 1)) {
            var newpos = st_array[0];
            //st_currentpos = 0;
          } else {
            var newpos = st_array[st_currentpos + 1];
          }

          var newimg = "<img class='new' src='" + newpos + "' alt='" + options.alttext + "' style='display: none; width: " + ciwidth + "px; height: " + ciheight + "px; margin-top: " + citop + "; margin-left: " + cileft + "'" + " />";

          st_container.append(newimg).onImagesLoad({
            selectorCallback: function() {
              $("img.new", st_container).fadeIn(st_fadingspeed, function() {
                $(currentimg).remove();
                $(this).removeClass("new").addClass("stretch");
                if (st_currentpos == (st_bgcount - 1)) {
                  st_currentpos = 0;
                } else {
                  st_currentpos++;
                }
                console.log("st_currentpos (after): " + st_currentpos);
                console.log("------------------------");
              });
            }
          });

        }

        setInterval(FadeImages, st_interval);

      }

      // DIFFER BETWEEN ONE IMAGE AND MORE THAN ONE (ONIMAGESLOAD PLUGIN)
      if (st_bgcount > 1) {
        Fader(st_fadingspeed, st_interval, st_container);
      }

      // WHAT HAPPENS WHEN WINDOW IS BEING RESIZED?
      $(window).resize(function() {
        ChangeSizesAndPositions();
      });

    });
  };
})(jQuery);
ready
backstretch
/*
 * jQuery Backstretch
 * Version 1.2.3
 * http://srobbin.com/jquery-plugins/jquery-backstretch/
 *
 * Add a dynamically-resized background image to the page
 *
 * Copyright (c) 2011 Scott Robbin (srobbin.com)
 * Dual licensed under the MIT and GPL licenses.
*/

(function($) {

  $.backstretch = function(src, options, callback) {
    var defaultSettings = {
      centeredX: true,
      // Should we center the image on the X axis?
      centeredY: true,
      // Should we center the image on the Y axis?
      speed: 0 // fadeIn speed for background after image loads (e.g. "fast" or 500)
    },
        container = $("#backstretch"),
        settings = container.data("settings") || defaultSettings,
         // If this has been called once before, use the old settings as the default
        existingSettings = container.data('settings'),
        rootElement = ("onorientationchange" in window) ? $(document) : $(window),
         // hack to acccount for iOS position:fixed shortcomings
        imgRatio, bgImg, bgWidth, bgHeight, bgOffset, bgCSS;

    // Extend the settings with those the user has provided
    if (options && typeof options == "object") $.extend(settings, options);

    // Initialize
    $(document).ready(_init);

    // For chaining
    return this;

    function _init() {
      // Prepend image, wrapped in a DIV, with some positioning and zIndex voodoo
      if (src) {
        var img;

        // If this is the first time that backstretch is being called
        if (container.length == 0) {
          container = $("<div />").attr("id", "backstretch").css({
            left: 0,
            top: 0,
            position: "fixed",
            overflow: "hidden",
            zIndex: -999999,
            margin: 0,
            padding: 0,
            height: "100%",
            width: "100%"
          });
        } else {
          // Prepare to delete any old images
          container.find("img").addClass("deleteable");
        }

        img = $("<img />").css({
          position: "absolute",
          display: "none",
          margin: 0,
          padding: 0,
          border: "none",
          zIndex: -999999
        }).bind("load", function(e) {
          var self = $(this),
              imgWidth, imgHeight;

          self.css({
            width: "auto",
            height: "auto"
          });
          imgWidth = this.width || $(e.target).width();
          imgHeight = this.height || $(e.target).height();
          imgRatio = imgWidth / imgHeight;

          _adjustBG(function() {
            self.fadeIn(settings.speed, function() {
              // Remove the old images, if necessary.
              container.find('.deleteable').remove();
              // Callback
              if (typeof callback == "function") callback();
            });
          });

        }).appendTo(container);

        // Append the container to the body, if it's not already there
        if ($("body #backstretch").length == 0) {
          $("body").append(container);
        }

        // Attach the settings
        container.data("settings", settings);

        img.attr("src", src); // Hack for IE img onload event
        // Adjust the background size when the window is resized or orientation has changed (iOS)
        $(window).resize(_adjustBG);
      }
    }

    function _adjustBG(fn) {
      try {
        bgCSS = {
          left: 0,
          top: 0
        }
        bgWidth = rootElement.width();
        bgHeight = bgWidth / imgRatio;

        // Make adjustments based on image ratio
        // Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
        if (bgHeight >= rootElement.height()) {
          bgOffset = (bgHeight - rootElement.height()) / 2;
          if (settings.centeredY) $.extend(bgCSS, {
            top: "-" + bgOffset + "px"
          });
        } else {
          bgHeight = rootElement.height();
          bgWidth = bgHeight * imgRatio;
          bgOffset = (bgWidth - rootElement.width()) / 2;
          if (settings.centeredX) $.extend(bgCSS, {
            left: "-" + bgOffset + "px"
          });
        }

        $("#backstretch, #backstretch img").width(bgWidth).height(bgHeight).filter("img").css(bgCSS);
      } catch (err) {
        // IE7 seems to trigger _adjustBG before the image is loaded.
        // This try/catch block is a hack to let it fail gracefully.
      }

      // Executed the passed in function, if necessary
      if (typeof fn == "function") fn();
    }
  };

})(jQuery);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by elstretch on