// ==UserScript==
// @name Web Comprehensive Optimization Script(web综合优化脚本)
// @namespace http://tampermonkey.net/
// @version 2.2
// @description Optimize non-first screen CSS and image lazy loading, hardware acceleration, script lazy loading, code splitting, caching strategy, event throttling, and more.
// @author KiwiFruit
// @match *://*/*
// @grant none
// @license MIT
// ==/UserScript==
(function() {
'use strict';
// 定义 calculateRootMargin 在最前面
function calculateRootMargin() {
const windowHeight = window.innerHeight;
const marginBottom = Math.max(0, windowHeight * 0.1); // 例如,取窗口高度的10%
return `0px 0px ${marginBottom}px 0px`;
}
// 命名空间封装
const WebOptimization = (function() {
// 模块:加载外部资源
const Loader = {
loadResource(url, type) {
return new Promise((resolve, reject) => {
const element = document.createElement(type === 'script' ? 'script' : 'link');
if (type === 'script') {
element.src = url;
} else {
element.rel = 'stylesheet';
element.href = url;
}
element.onload = resolve;
element.onerror = () => reject(new Error(`${type} loading failed: ${url}`));
document.head.appendChild(element);
});
},
loadScript(url) {
return this.loadResource(url, 'script');
},
loadStylesheet(href) {
return this.loadResource(href, 'stylesheet');
}
};
// 模块:硬件加速
const HardwareAcceleration = (() => {
const className = 'enable-hardware-acceleration';
const styleSheet = `
.${className} {
transform: translateZ(0) !important; /* 使用 !important 提高样式优先级 */
will-change: transform !important;
}
`;
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add(className);
} else {
entry.target.classList.remove(className);
}
});
}, { rootMargin: calculateRootMargin(), threshold: 0 });
function init() {
const styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.appendChild(document.createTextNode(styleSheet));
document.head.appendChild(styleElement);
}
return {
init,
observe(element) {
observer.observe(element);
}
};
})();
// 模块:懒加载
const LazyLoading = {
initializeImageLazyLoading() {
const scriptUrl = 'https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.15.0/lozad.min.js';
Loader.loadResource(scriptUrl, 'script')
.then(() => {
if (typeof window.lozad === 'function') {
const observer = window.lozad();
observer.observe();
} else {
console.error('Lozad.js failed to load or did not expose the expected global function.');
}
})
.catch(error => console.error('Failed to load Lozad script:', error));
},
initializeNonFirstScreenCssLazyLoading() {
const elements = document.querySelectorAll('.lazy-css');
elements.forEach(element => {
const href = element.getAttribute('data-lazy-css');
if (href) {
Loader.loadStylesheet(href)
.then(() => element.parentElement.removeChild(element))
.catch(error => console.error('Failed to load lazy CSS:', error));
}
});
},
initializeMediaPlayback() {
const mediaElements = document.querySelectorAll('audio, video');
mediaElements.forEach(element => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
element.play();
} else {
element.pause();
}
});
}, { rootMargin: '0px', threshold: 0 });
observer.observe(element);
});
}
};
// 模块:事件处理
const Events = {
throttle(func, wait) {
let timeoutId = null;
return (...args) => {
if (!timeoutId) {
timeoutId = setTimeout(() => {
func.apply(this, args);
timeoutId = null;
}, wait);
}
};
},
debounce(func, wait) {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), wait);
};
},
handleScroll() {
const throttledScrollHandler = this.throttle(() => {
console.log('Scroll event triggered');
}, 100);
window.addEventListener('scroll', throttledScrollHandler.bind(this));
}
};
// 初始化示例
function initialize() {
if (checkBrowserCompatibility()) {
// 初始化模块
HardwareAcceleration.init();
LazyLoading.initializeImageLazyLoading();
LazyLoading.initializeNonFirstScreenCssLazyLoading();
LazyLoading.initializeMediaPlayback();
Events.handleScroll();
// 并行加载多个资源
const resourcesToLoad = [
{ url: 'https://example.com/script1.js', type: 'script' },
{ url: 'https://example.com/style1.css', type: 'stylesheet' },
{ url: 'https://example.com/script2.js', type: 'script' },
{ url: 'https://example.com/style2.css', type: 'stylesheet' }
];
const loadPromises = resourcesToLoad.map(resource =>
Loader.loadResource(resource.url, resource.type)
.then(() => ({
status: 'fulfilled',
value: `${resource.type} loaded: ${resource.url}`
}))
.catch(error => ({
status: 'rejected',
reason: `Failed to load ${resource.type}: ${resource.url}, Error: ${error.message}`
}))
);
Promise.allSettled(loadPromises).then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log(result.value);
} else {
console.error(result.reason);
}
});
// 在这里可以执行资源释放或其他清理操作
});
// 监听 DOM 变化
const mutationObserver = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node.nodeType === 1) {
if (node.tagName === 'IMG' && node.hasAttribute('data-src')) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
node.src = node.getAttribute('data-src');
observer.unobserve(node);
}
});
}, { rootMargin: calculateRootMargin(), threshold: 0 });
observer.observe(node);
} else if (node.classList.contains('lazy-css') && node.hasAttribute('data-lazy-css')) {
const href = node.getAttribute('data-lazy-css');
Loader.loadStylesheet(href)
.then(() => node.parentElement.removeChild(node))
.catch(error => console.error('Failed to load lazy CSS:', error));
} else if (node.matches('.target-element')) {
HardwareAcceleration.observe(node);
}
}
});
});
});
mutationObserver.observe(document.body, { childList: true, subtree: true });
// Resize Observer
const resizeObserver = new ResizeObserver(() => {
requestAnimationFrame(() => {
// Reapply hardware acceleration or other necessary adjustments
});
});
resizeObserver.observe(document.body);
}
}
// 浏览器兼容性检查
function checkBrowserCompatibility() {
const isSupported = !!window.IntersectionObserver && !!window.ResizeObserver;
if (!isSupported) {
console.warn('Your browser does not support some required features.');
}
return isSupported;
}
return {
initialize
};
})();
// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", function() {
WebOptimization.initialize();
});
})();