Faster Webpage Loading

Preload subsequent pages and lazy load images to speed up webpage loading

当前为 2024-09-04 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Faster Webpage Loading
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.2
  5. // @description Preload subsequent pages and lazy load images to speed up webpage loading
  6. // @author tae
  7. // @match *://*/*
  8. // @grant none
  9. // ==/UserScript==
  10.  
  11. (function() {
  12. 'use strict';
  13.  
  14. // Lazy load images
  15. document.addEventListener("DOMContentLoaded", function() {
  16. let lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
  17. if ("IntersectionObserver" in window) {
  18. let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
  19. entries.forEach(function(entry) {
  20. if (entry.isIntersecting) {
  21. let lazyImage = entry.target;
  22. lazyImage.src = lazyImage.dataset.src;
  23. lazyImage.classList.remove("lazy");
  24. lazyImageObserver.unobserve(lazyImage);
  25. }
  26. });
  27. });
  28.  
  29. lazyImages.forEach(function(lazyImage) {
  30. lazyImageObserver.observe(lazyImage);
  31. });
  32. } else {
  33. // Fallback for browsers without IntersectionObserver support
  34. let lazyLoad = function() {
  35. lazyImages.forEach(function(lazyImage) {
  36. if (lazyImage.getBoundingClientRect().top < window.innerHeight && lazyImage.getBoundingClientRect().bottom > 0 && getComputedStyle(lazyImage).display !== "none") {
  37. lazyImage.src = lazyImage.dataset.src;
  38. lazyImage.classList.remove("lazy");
  39. }
  40. });
  41. if (lazyImages.length === 0) {
  42. document.removeEventListener("scroll", lazyLoad);
  43. window.removeEventListener("resize", lazyLoad);
  44. window.removeEventListener("orientationchange", lazyLoad);
  45. }
  46. };
  47.  
  48. document.addEventListener("scroll", lazyLoad);
  49. window.addEventListener("resize", lazyLoad);
  50. window.addEventListener("orientationchange", lazyLoad);
  51. }
  52. });
  53.  
  54. // Preload subsequent pages
  55. document.addEventListener("mouseover", function(event) {
  56. if (event.target.tagName === 'A' && event.target.href) {
  57. let link = event.target.href;
  58. let prefetchLink = document.createElement('link');
  59. prefetchLink.rel = 'prefetch';
  60. prefetchLink.href = link;
  61. document.head.appendChild(prefetchLink);
  62. }
  63. });
  64. })();