Enhanced Faster Webpage Loading (Optimized)

Optimize webpage loading with native prefetching, priority hints, and lazy loading.

  1. // ==UserScript==
  2. // @name Enhanced Faster Webpage Loading (Optimized)
  3. // @namespace http://tampermonkey.net/
  4. // @version 3.0
  5. // @description Optimize webpage loading with native prefetching, priority hints, and lazy loading.
  6. // @match *://*/*
  7. // @grant none
  8. // @run-at document-end
  9. // ==/UserScript==
  10.  
  11. (function () {
  12. 'use strict';
  13.  
  14. const EXCLUDED_LINKS = ['/login', '/logout', '/signout', '/signin', '/account', '/auth'];
  15.  
  16. // Lazy Load Images, Videos, and Iframes
  17. function setupLazyLoading(root = document) {
  18. const lazyElements = root.querySelectorAll("img[data-src], video[data-src], iframe[data-src]");
  19.  
  20. function loadLazyElement(el) {
  21. if (el.dataset.src) {
  22. el.src = el.dataset.src;
  23. if (el.tagName.toUpperCase() === "VIDEO") el.load();
  24. el.removeAttribute("data-src");
  25. }
  26. }
  27.  
  28. if ("IntersectionObserver" in window) {
  29. const observer = new IntersectionObserver((entries, observerInstance) => {
  30. entries.forEach(entry => {
  31. if (entry.isIntersecting) {
  32. loadLazyElement(entry.target);
  33. observerInstance.unobserve(entry.target);
  34. }
  35. });
  36. });
  37. lazyElements.forEach(el => observer.observe(el));
  38. } else {
  39. lazyElements.forEach(loadLazyElement);
  40. }
  41. }
  42.  
  43. // Prefetch and Prioritize Links
  44. function enhancePrefetching() {
  45. document.querySelectorAll("a[href]").forEach(link => {
  46. const href = link.href;
  47. if (!EXCLUDED_LINKS.some(excluded => href.includes(excluded)) && !link.hasAttribute("data-no-prefetch")) {
  48. const prefetch = document.createElement("link");
  49. prefetch.rel = "prefetch";
  50. prefetch.href = href;
  51. prefetch.as = "document";
  52. document.head.appendChild(prefetch);
  53.  
  54. // Use Priority Hints (if supported)
  55. link.setAttribute("importance", "high");
  56. }
  57. });
  58. }
  59.  
  60. // Watch for dynamically added content
  61. function observeDynamicContent() {
  62. const observer = new MutationObserver(mutations => {
  63. mutations.forEach(mutation => {
  64. mutation.addedNodes.forEach(node => {
  65. if (node.nodeType === 1) {
  66. setupLazyLoading(node);
  67. enhancePrefetching();
  68. }
  69. });
  70. });
  71. });
  72. observer.observe(document.body, { childList: true, subtree: true });
  73. }
  74.  
  75. // Initialize Enhancements
  76. function init() {
  77. setupLazyLoading();
  78. enhancePrefetching();
  79. observeDynamicContent();
  80. }
  81.  
  82. if (document.readyState === "loading") {
  83. document.addEventListener("DOMContentLoaded", init);
  84. } else {
  85. init();
  86. }
  87. })();