lazyload.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /**
  2. * Copyright © 2015-2017 Ihor Vansach (ihor@magefan.com). All rights reserved.
  3. * See LICENSE.txt for license details (http://opensource.org/licenses/osl-3.0.php).
  4. *
  5. * Glory to Ukraine! Glory to the heroes!
  6. */
  7. /**
  8. * Posts autload
  9. */
  10. define([
  11. 'domReady!',
  12. 'jquery'
  13. ], function (domReady, $) {
  14. 'use strict';
  15. var Lazyload = function(options) {
  16. var that = this;
  17. /**
  18. * Lazyload default options.
  19. * @type {Object}
  20. */
  21. that.defaults = {
  22. expires: null,
  23. path: '/',
  24. domain: null,
  25. secure: false,
  26. lifetime: null
  27. };
  28. /**
  29. * Init options
  30. * @type {Object}
  31. */
  32. that.opt = $.extend(that.default, options);
  33. /**
  34. * Load new content
  35. */
  36. function startLoading()
  37. {
  38. if (that.opt.current_page < that.opt.last_page && !that.loading) {
  39. that.loading = true;
  40. $('.mfblog-show-onload').show();
  41. $('.mfblog-hide-onload').hide();
  42. $.ajax({
  43. "url":that.opt.page_url[that.opt.current_page+1],
  44. "cache":true
  45. }).success(function(data) {
  46. var $html = $(data);
  47. var ws = that.opt.list_wrapper;
  48. var $nw = $html.find(ws);
  49. if ($nw.length) {
  50. $(ws).append($nw.html());
  51. that.opt.current_page++;
  52. }
  53. endLoading();
  54. }).fail(function(xhr, ajaxOptions, thrownError) {
  55. console.log(thrownError);
  56. endLoading();
  57. });
  58. }
  59. }
  60. /**
  61. * On loading end
  62. */
  63. function endLoading() {
  64. that.loading = false;
  65. $('.mfblog-show-onload').hide();
  66. if (that.opt.current_page < that.opt.last_page) {
  67. $('.mfblog-hide-onload').show();
  68. }
  69. }
  70. /* Is not loading now */
  71. endLoading();
  72. /* If auto trigger enabled */
  73. if (that.opt.auto_trigger) {
  74. var $w = $(window);
  75. $w.scroll(function() {
  76. if ($w.scrollTop() + $w.height() >= $(that.opt.trigger_element).offset().top - that.opt.padding) {
  77. startLoading();
  78. }
  79. });
  80. }
  81. /* On trigger element click */
  82. if (that.opt.trigger_element) {
  83. $(that.opt.trigger_element).click(function(){
  84. startLoading();
  85. });
  86. }
  87. }
  88. return function (options) {
  89. new Lazyload(options)
  90. };
  91. });