Tavriav Lazy Load Scroll

Lazy load two subsequent pages on Tavriav's catalog pages with 1-second delay, display current page number, and show distance from the bottom

当前为 2023-10-20 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Tavriav Lazy Load Scroll
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description Lazy load two subsequent pages on Tavriav's catalog pages with 1-second delay, display current page number, and show distance from the bottom
  6. // @author You
  7. // @match https://www.tavriav.ua/catalog/*/?*
  8. // @grant GM_addStyle
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. let currentPage = parseInt(new URLSearchParams(window.location.search).get('page'), 10) || 1;
  16. const distanceFromBottom = 4000;
  17. let loading = false;
  18. let pagesToLoad = 2;
  19.  
  20. // Create and style the display divs
  21. GM_addStyle(`
  22. #displayDiv {
  23. position: fixed;
  24. top: 10px;
  25. left: 10px;
  26. background: rgba(0,0,0,0.7);
  27. color: #fff;
  28. padding: 5px 10px;
  29. border-radius: 5px;
  30. font-size: 14px;
  31. z-index: 1000;
  32. }
  33. `);
  34.  
  35. const pageNumberDisplay = document.createElement('div');
  36. pageNumberDisplay.id = "displayDiv";
  37. document.body.appendChild(pageNumberDisplay);
  38.  
  39. window.addEventListener('scroll', () => {
  40. const distance = document.body.offsetHeight - (window.innerHeight + window.scrollY);
  41. pageNumberDisplay.innerHTML = `Page: ${currentPage}<br>Distance from bottom: ${Math.round(distance)}px`;
  42.  
  43. if (!loading && distance <= distanceFromBottom) {
  44. currentPage++;
  45. loadMultiplePages(currentPage, pagesToLoad);
  46. }
  47. });
  48.  
  49. function appendContent(text) {
  50. const parser = new DOMParser();
  51. const doc = parser.parseFromString(text, 'text/html');
  52. const newContent = doc.querySelector('.catalog-products__container');
  53.  
  54. if (newContent) {
  55. document.querySelector('.catalog-products__container').appendChild(newContent);
  56. }
  57. }
  58.  
  59. function fetchPage(pageNum) {
  60. const currentURL = new URL(window.location.href);
  61. const params = currentURL.searchParams;
  62. params.set('page', pageNum);
  63.  
  64. return fetch(`${currentURL.origin}${currentURL.pathname}?${params.toString()}`)
  65. .then(response => response.text());
  66. }
  67.  
  68. function loadMultiplePages(startPage, count) {
  69. if (count === 0) {
  70. loading = false;
  71. return;
  72. }
  73.  
  74. loading = true;
  75. fetchPage(startPage).then(text => {
  76. appendContent(text);
  77. setTimeout(() => {
  78. loadMultiplePages(startPage + 1, count - 1);
  79. }, 1000); // 1-second delay before fetching the next page
  80. });
  81. }
  82.  
  83. loadMultiplePages(currentPage + 1, pagesToLoad); // Start fetching the next two pages immediately
  84. })();
  85.