Greasy Fork is available in English.
Boost website loading speed, prevent autoplay for YouTube videos, and lazy load images and videos.
当前为
// ==UserScript==
// @name Super Fast Loading Optimized
// @namespace http://tampermonkey.net/
// @version 1.2
// @description Boost website loading speed, prevent autoplay for YouTube videos, and lazy load images and videos.
// @author Farzan Farhangi
// @match *://*/*
// @grant GM_xmlhttpRequest
// ==/UserScript==
(function() {
'use strict';
const allowAutoPlayWithinMillisecondsOfClick = 1000;
let lastClickTimeMs = 0;
// Function to prevent autoplay for YouTube videos
const preventAutoplayYouTube = () => {
const videos = document.querySelectorAll('video[data-src]');
videos.forEach(video => {
video.pause();
video.removeAttribute('src');
video.addEventListener('click', () => {
if (!video.src) {
const source = video.getAttribute('data-src');
if (source) {
video.src = source;
video.play();
}
}
});
});
};
// Lazy load videos
const lazyLoadVideos = () => {
const videos = document.querySelectorAll('video[data-src]');
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const video = entry.target;
video.src = video.getAttribute('data-src');
video.play();
observer.unobserve(video);
}
});
});
videos.forEach(video => observer.observe(video));
};
// Check if autoplay is allowed based on last click time
const isAutoPlayAllowed = () => (Date.now() - lastClickTimeMs) <= allowAutoPlayWithinMillisecondsOfClick;
window.addEventListener('click', () => { lastClickTimeMs = Date.now(); });
// Enable lazy loading for images
const enableLazyLoadImages = () => {
const images = document.querySelectorAll('img:not([loading])');
images.forEach(img => img.setAttribute('loading', 'lazy'));
};
// Load scripts asynchronously
const loadScriptAsync = (url) => {
const script = document.createElement('script');
script.src = url;
script.defer = true; // Load asynchronously without blocking rendering
document.head.appendChild(script);
};
// Load CSS immediately
const loadCSS = (url) => {
const link = document.createElement('link');
link.rel ='stylesheet';
link.href = url;
document.head.appendChild(link);
};
// Preload critical resources at the start
const preloadResources = async () => {
const criticalResources = [
'https://example.com/styles.css',
'https://example.com/script.js',
// Add other resources here as needed
];
criticalResources.forEach(resource => {
if (resource.endsWith('.css')) {
loadCSS(resource);
} else if (resource.endsWith('.js')) {
loadScriptAsync(resource);
}
});
};
window.addEventListener('load', () => {
enableLazyLoadImages();
preloadResources();
preventAutoplayYouTube();
lazyLoadVideos(); // Call lazy loading for videos after page load
});
})();