The FREE last-ditch effort pagespeed optimization script

Speed up your unfixable page with this last ditch effort method to improve even the slowest pages

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

The FREE last-ditch effort pagespeed optimization script

Sometimes, as a Core Web Vitals consultant, I come across the unfixable page. It is not that it is unfixable because I do not know how to fix it! No, it is unfixable because fixing it would mean rewriting large parts of a site that is already scheduled to be replaced. Or sometimes when there is just not enough access and control to improve the site's code as you see with more closed CMS systems like WIX, HubSpot, WebFlow etc. Or, lastly, when the budget is just not there. It does not happen often yet sometimes clients can not accurately predict the amount of work that needs to be done and paid for.

Last reviewed by Arjen Karel on March 2026

Introducing "The last-ditch pagespeed optimization script"

When you find yourself in this tight spot, this script is your desperate final attempt to at least improve the pagespeed a little bit until you can build something better. It cleverly works by using the Mutation Observer. The script watches as the Document Object Model of your site is being created by the browser and immediately intercepts and replaces slow code by faster code.

What it does:

  • Intercept all render blocking scripts and defer them by changing the type of the script to type="module". This trick makes use of the fact that all modular scripts are deferred by default. Even inline scripts. This makes this the most safe method to defer all page scripts.
  • Lazy image loading: loading="lazy" and decoding="async" is added to all images. This will defer the loading of these images until they are almost in the visible viewport along with asynchronous image layout updating. Be careful: you do not want to lazy load your LCP image. Use the prioImgs config to exclude it. See why lazy loading the LCP image hurts performance.
  • Lazy load iframes. Same as with images, lazy loading iframes can prioritize your own, more important, content!

Configuration

The script takes a single "config object" and uses that config to skip deferring or lazy loading important images and scripts. For iframes it works the other way around, it only lazy loads the iframes that match your config. All configurations come as a regular expression. That may sound scary but in practice it is really simple.

  • prioScripts: Skips deferring scripts where the src matches the configuration.
    Example: 'jquery|menu' matches your jquery and your menu script
  • prioImgs: Skips lazy loading for all images where the image name, image class or image id matches.
    Example: 'hero' matches both <img id="hero" ..> and <img src="hero.jpg">
  • lazyFrames: Lazy loads only iframes where the iframe src matches the config.
    Example: 'youtube|maps' lazy loads all YouTube and Google Maps iframes.

Usage

Just edit the config to make it match your website's needs and paste in first thing into the head of the page. Remember: the script can only fix issues after it has been found. So the lower you place it in the head of the page the less effective it will be!

Limitations

As I previously stated you should really not be using this script as your main solution to fix your pagespeed. Only when all else fails, while you are actively working on a new site, is a solution like this acceptable!
In more technical terms this script races against the browser (and the preload scanner) so there is no telling which slow elements will have already been triggered for download before the script activates.

The last-ditch pagespeed optimization script

Here is a minified version that should be used in production

!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"});

Here is a more readable version of the script. Do not use this in production! Use the minified one!

!function (cfg) {\r\n\r\n    // Regexify config or nullify\r\n    ['prioScripts', 'prioImgs', 'lazyFrames'].forEach((e) => {\r\n        cfg[e] = cfg[e] ? new RegExp(cfg[e], "i") : null;\r\n    });\r\n\r\n    t0 = performance.now();\r\n\r\n    /* Watch mutated nodes */\r\n    const mutator = new MutationObserver((e) => {\r\n        e.forEach(({ addedNodes: e }) => {\r\n            e.forEach((e) => {\r\n                switch (e.nodeType) {\r\n                    case 1:\r\n                        switch (e.tagName) {\r\n                            // defer scripts by adding type="module", excusive test on src\r\n                            case "SCRIPT":\r\n                                if (!cfg.prioScripts || !cfg.prioScripts.test(e.src)) {\r\n                                    let type = e.getAttribute("type");\r\n                                    if (!type || type === "text/javascript") {\r\n                                        e.setAttribute("type", "module");\r\n                                    }\r\n                                }\r\n                                break;\r\n\r\n                            // lazy load images, excusive test on outerHTML for classname, id etc etc\r\n                            case "IMG":\r\n                                console.log(e.outerHTML);\r\n                                if (!cfg.prioImgs || (!cfg.prioImgs.test(e.outerHTML) && !e.getAttribute("loading"))) {\r\n                                    e.setAttribute("loading", "lazy");\r\n                                    e.setAttribute("decoding", "async");\r\n                                }\r\n                                break;\r\n\r\n                            // lazy load iframes, inclusive test on src\r\n                            case "IFRAME":\r\n                                if (cfg.lazyFrames.test(e.src)) {\r\n                                    e.setAttribute("loading", "lazy");\r\n                                }\r\n                                break;\r\n                        }\r\n                        break;\r\n                }\r\n            });\r\n        });\r\n    });\r\n\r\n\r\n    // Check for IE\r\n    if (!/MSIE|Trident/.test(navigator.userAgent)) {\r\n        mutator.observe(document.documentElement, { childList: true, subtree: true });\r\n        document.addEventListener("DOMContentLoaded", () => {\r\n            mutator.disconnect();\r\n            console.log("I quit after watching for " + (performance.now() - t0) + " ms");\r\n        });\r\n    }\r\n}({\r\n    prioScripts: 'jquery',\r\n    prioImgs: 'hero',\r\n    lazyFrames: 'youtube|maps',\r\n});\r\n\r\n\r\n

About the author

Arjen Karel is a web performance consultant and the creator of CoreDash, a Real User Monitoring platform that tracks Core Web Vitals data across hundreds of sites. He also built the Core Web Vitals Visualizer Chrome extension. He has helped clients achieve passing Core Web Vitals scores on over 925,000 mobile URLs.

Ask AI why your INP spiked.

CoreDash is the only RUM tool with MCP support. Connect it to your AI agent and query your Core Web Vitals data in natural language. No more clicking through dashboards.

See How It Works
The FREE last-ditch effort pagespeed optimization scriptCore Web Vitals The FREE last-ditch effort pagespeed optimization script