免费的最后手段页面速度优化脚本

用这个最后手段的方法加速你无法修复的页面,即使是最慢的页面也能得到改善

Arjen Karel Core Web Vitals Consultant
Arjen Karel - linkedin
Last update: 2026-02-07

免费的最后手段页面速度优化脚本

有时候,作为一名 Core Web Vitals 顾问,我会遇到无法修复的页面。这不是因为我不知道如何修复它! 
不,它无法修复是因为修复它意味着要重写一个已经计划被替换的网站的大部分内容。或者有时候,当没有足够的访问权限和控制权来改善网站的代码时,就像你在更封闭的 CMS 系统中看到的那样,比如  (WIX, HubSpot, WebFlow 等)。或者,最后,当预算不够的时候。这种情况并不经常发生,但有时客户无法准确预测需要完成和支付的工作量。

介绍“最后手段页面速度优化脚本”

当你发现自己处于这种困境中时,这个脚本就是你最后的孤注一掷的尝试,至少可以稍微改善页面速度,直到你能构建出更好的解决方案。它巧妙地利用了 Mutation Observer。该脚本会监视浏览器创建你网站的 Document Object Model 的过程,并立即拦截慢速代码并替换为更快的代码。

它的功能:

  • 拦截所有阻塞渲染的脚本,并通过将脚本类型更改为 type="module" 来延迟加载它们。这个技巧利用了所有模块化脚本默认都是延迟加载的这一事实。即使是内联脚本也是如此。这使得这成为延迟加载所有页面脚本的最安全方法。
  • 图片懒加载:为所有图片添加 loading="lazy"decoding="async" 。这将把这些图片的加载推迟到它们几乎进入可见视口时,同时进行异步图片布局更新。
  • 懒加载 iframe。与图片相同,懒加载 iframe 可以优先加载你自己更重要的内容!

配置

该脚本接受一个‘配置对象’,并使用该配置来跳过延迟加载或懒加载重要的图片和脚本。对于 iframe,它的工作方式相反,它只懒加载与你的配置匹配的 iframe。所有配置都以正则表达式的形式出现。这听起来可能很吓人,但在实践中其实非常简单。这里 

  • prioScripts:跳过延迟加载 src 与配置匹配的脚本。
  • 示例:'jquery|menu' 匹配你的 jquery 和菜单脚本
  • prioImgs:跳过懒加载所有图片名称、图片 class 或图片 id 匹配的图片
    示例:'hero' 同时匹配 <img id="hero" ..> 和 <img src="hero.jpg">
  • lazyFrames:仅懒加载 iframe src 与配置匹配的 iframe。
    示例:'youtube|maps' 懒加载所有 youtube 和 Google Maps iframe。

用法

只需编辑配置使其匹配你网站的需求,然后将其粘贴到页面 head 的最前面。记住:脚本只能修复它被发现之后的问题。因此,你在页面 head 中放置的位置越低,它的效果就越差!

局限性

正如我之前所说,你真的不应该将此脚本用作修复页面速度的主要解决方案。只有在所有其他方法都失败了,而你正在积极开发新网站时,这样的解决方案才是可以接受的!
从更技术性的角度来说,这个脚本与浏览器(和 preload scanner)竞争,所以无法预知哪些慢速元素在脚本激活之前就已经被触发下载了。

最后手段页面速度优化脚本

这是一个应该在生产环境中使用的压缩版本

!function(t){['prioScripts', 'prioImgs', 'lazyFrames'].forEach(e=>{t[e]=t[e]?RegExp(t[e],"i"):null});let e=new MutationObserver(e=>{e.forEach(({addedNodes:e})=>{e.forEach(e=>{if(1===e.nodeType)switch(e.tagName){case"SCRIPT":if(!t.prioScripts||!t.prioScripts.test(e.src)){let t=e.getAttribute("type");t&&"text/javascript"!==t||e.setAttribute("type","module")}break;case"IMG":console.log(e.outerHTML),t.prioImgs&&(t.prioImgs.test(e.outerHTML)||e.getAttribute("loading"))||(e.setAttribute("loading","lazy"),e.setAttribute("decoding","async"));break;case"IFRAME":t.lazyFrames.test(e.src)&&e.setAttribute("loading","lazy")}})})});/MSIE|Trident/.test(navigator.userAgent)||(e.observe(document.documentElement,{childList:!0,subtree:!0}),document.addEventListener("DOMContentLoaded",()=>{e.disconnect()}))}({prioScripts:"jquery",prioImgs:"hero",lazyFrames:"youtube|maps"});

这是一个更易读的脚本版本。不要在生产环境中使用!请使用压缩版!

!function (cfg) {

    // Regexify config or nullify
    ['prioScripts', 'prioImgs', 'lazyFrames'].forEach((e) => {
        cfg[e] = cfg[e] ? new RegExp(cfg[e], "i") : null;
    });

    t0 = performance.now();

    /* Watch mutated nodes */
    const mutator = new MutationObserver((e) => {
        e.forEach(({ addedNodes: e }) => {
            e.forEach((e) => {
                switch (e.nodeType) {
                    case 1:
                        switch (e.tagName) {
                            // defer scripts by adding type="module", excusive test on src
                            case "SCRIPT":
                                if (!cfg.prioScripts || !cfg.prioScripts.test(e.src)) {
                                    let type = e.getAttribute("type");
                                    if (!type || type === "text/javascript") {
                                        e.setAttribute("type", "module");
                                    }
                                }
                                break;

                            // lazy load images, excusive test on outerHTML for classname, id etc etc
                            case "IMG":
                                console.log(e.outerHTML);
                                if (!cfg.prioImgs || (!cfg.prioImgs.test(e.outerHTML) && !e.getAttribute("loading"))) {
                                    e.setAttribute("loading", "lazy");
                                    e.setAttribute("decoding", "async");
                                }
                                break;

                            // lazy load iframes, inclusive test on src
                            case "IFRAME":
                                if (cfg.lazyFrames.test(e.src)) {
                                    e.setAttribute("loading", "lazy");
                                }
                                break;
                        }
                        break;
                }
            });
        });
    });


    // Check for IE
    if (!/MSIE|Trident/.test(navigator.userAgent)) {
        mutator.observe(document.documentElement, { childList: true, subtree: true });
        document.addEventListener("DOMContentLoaded", () => {
            mutator.disconnect();
            console.log("I quit after watching for " + (performance.now() - t0) + " ms");
        });
    }
}({
    prioScripts: 'jquery',
    prioImgs: 'hero',
    lazyFrames: 'youtube|maps',
});


免费的最后手段页面速度优化脚本Core Web Vitals 免费的最后手段页面速度优化脚本