Stop pasting scripts into Webflow page settings: keep your custom code in a repo

Saif Ali, MVP developer7 years across design, Webflow, Next.js and full appsLast updated · 20 min read
In shortMove Webflow custom code out of page settings and into a Git repo, one small JavaScript component per behaviour. Add one loader script to the site head, then mark elements in the Designer with a custom attribute such as ss-component="lazy-video". The loader starts the matching code, so behaviour travels with the component to any page. On one large site, this replaced a lazy-video snippet copied onto 8 pages, and the loader costs about 1.3 kB (gzipped) on pages with no components.
Rather hand it over? I do this for clients →
If you build in Webflow, you have probably pasted a script into page settings or a Code Embed element (previously HTML Embed). It works. Then a second page needs the same thing, so you copy it. Soon there are several copies, and nobody knows which one is right.
This guide shows a different way to work: your Webflow components should carry their own behaviour. The code lives in a repo where it is versioned and tested, and a component dropped onto any page just works. You don't need to have done this before. Every term is explained the first time it comes up.
The problem, in numbers
We audit a lot of Webflow sites, and the story is nearly always the same: hundreds of small scripts pasted into site settings, page settings and Code Embeds, many of them copies of each other. No one planned it. Each snippet solved one problem on one page, and then it got copied.
Here's what that looked like on one large corporate site:
- Hundreds of snippets, most of them one-offs. 198 blocks of custom code across 52 pages, 143 of them unique, plus 63 more script and style blocks hidden inside Code Embeds.
- The same code, copied page to page. A lazy background-video loader was identical on 8 pages. A FAQ accordion was identical on 5 pages, plus 3 variants. A related-news slider existed in 3 different versions across 8 pages. A scroll-driven "sticky sequence" animation had 7 near-copies, about 69 kB of code in total.
- Libraries loaded several times, in different ways. Swiper came from a CDN on about 10 pages, in three different ways. GSAP was loaded site-wide as 3.12.2 and again as 3.12.5 on four pages. Some libraries had no version pinned. One page loaded a personal npm package at
@latest, so any publish to that package changed the live site. - Behaviour tied to pages. Copy a component to a new page and it looks right but does nothing, because its script lives in the old page's settings.
- No history, review or tests. An edited snippet goes live on the next publish, and nobody can see what changed.
- Hard for editors. Non-technical and new Webflow editors can't tell which code a component needs.
How the setup works: component JavaScript, loaded by attribute
- Page loads
- Loadertiny inline script, registered once in Webflow, applied site-wide in
<head>In Webflow - imports
/scripts/ss.jsfrom the site's own domain~1.3 kB gzippedWebflow Cloud - finds every element with
ss-component="<name>"On the page - downloads only that component's chunkand starts it on that elementOn the page
A few terms first:
- Custom attribute
- A name and value you add to any element in the Webflow Designer, under Element settings → Custom attributes. Here,
ss-component="lazy-video"says "this element needs the lazy-video code". - Loader
- A small script whose only job is to find those attributes on the page and fetch the matching code.
- Bundle and chunk
- A build tool turns your source files into a bundle, the main JavaScript file (
ss.js). Each component is split into its own chunk, a smaller file that only downloads when a page needs it. - Webflow Cloud
- Webflow's hosting for apps. We use it to serve the bundle at
/scriptson the site's own domain, so there is no third-party CDN and no cross-origin request. - Webflow Data API
- Webflow's API for changing a site with code instead of the Designer. In this guide it's one of two ways to add the loader (step 2).
The contract between the Designer and the code is the attribute. Designers can rename classes freely; the code never looks at them. Editors keep building in the Designer, and developers change code in the repo.
What you need before you start
- A Webflow site with a staging site: a copy where you can try changes before visitors see them. In Webflow, that is the site's Webflow-hosted address; your custom domain is production.
- A GitHub repo for the code, and Node.js with npm to install and run it. The Webflow CLI needs Node 22.13 or later.
- Webflow Cloud for the site, to host the bundle. No Cloud? Step 6 says what to do instead.
- A way to add the loader to the site head (step 2): a paid Site plan or paid Workspace for the head code field, or a Webflow App with Data API access.
- Enough JavaScript to read the samples below. You don't need to know Vite or Vitest yet.
This guide shows the pattern and the key files, not every file in the repo. New to repos? Use the prompt in the next section to scaffold it, then do steps 4, 5 and 7 yourself: they're the Webflow side.
Set it up with Claude: a prompt you can copy
If you'd rather have Claude scaffold this with you, copy the prompt below into Claude (or Claude Code, if it can see your project folder). Change the prefix to your own, and paste one of your existing snippets where it says so. It builds the same setup this guide walks through, one step at a time, and leaves every Webflow change to you.
Help me move the custom JavaScript on my Webflow site out of page settings and into a Git repo, so each component carries its own behaviour. Work step by step, show me the files you create, and wait for my OK before each step.
My setup:
- Attribute prefix: ss (change to your own short prefix)
- Webflow Cloud available: yes / no
- First snippet to convert (pasted below)
Build this:
1. A Vite project with plain JavaScript modules: src/main.js (entry, built as <prefix>.js), src/loader.js, src/lib/ for shared helpers, and one folder per component in src/components/<name>/index.js. Register components automatically with import.meta.glob, so each one becomes its own lazily loaded chunk. Build it with a relative base, so the chunks load from wherever <prefix>.js is served.
2. A loader that finds every element with <prefix>-component="<name>", loads only that component's chunk and calls its init(root). It must be safe to call again on new markup, skip roots it has already started, keep going if one component fails, set <prefix>-ready on started roots, and keep any cleanup function init returns.
3. Attribute rules: components only look inside their own root, never document.querySelector. Elements use <prefix>-<name>-el="<role>", and settings use <prefix>-<name>-<setting>. Never select by class or id.
4. Component CSS ships inside the component and is injected at runtime, scoped with attribute selectors, using logical properties (margin-inline-start, text-align: start) so right-to-left pages work.
5. Components add to native Webflow behaviour and never break it if the script fails.
6. Tests with Vitest and jsdom for every component, plus a dev page at dev/index.html with stand-in markup.
7. A Webflow loader under 2,000 characters for a site-wide inline script: it imports location.origin + '/scripts/<prefix>.js'. On *.webflow.io with ?local in the URL, it loads from the Vite dev server at http://localhost:5173 instead, and falls back to the deployed build if the dev server isn't running. Log to the console which build loaded. For this to work, vite.config.js keeps the dev server on port 5173 with strictPort: true, sets server.origin to 'http://localhost:5173', and sets server.cors to { origin: /^https:\/\/[^.]+\.webflow\.io$/ }, so only my *.webflow.io staging pages can load it (never cors: true).
8. If Webflow Cloud is available: a thin Astro shell mounted at /scripts that runs the Vite build into public/ and serves it, with server routes kept outside the Vite src/ folder (Astro's srcDir set to ./cloud) and a /scripts/health route that returns the deployed version. Don't set Astro's base; Webflow Cloud sets it from the mount path. If I don't have Webflow Cloud, stop after the build and tell me what to host where.
9. Convert my snippet into the first component. Keep its behaviour identical, and make sure it can run on the same page as the old snippet without doing the work twice.
Rules: pin exact versions of every dependency and tool, with no CDN links and no @latest. Don't change anything in Webflow yourself; give me the attribute to add and the snippet to remove, one page at a time.
My snippet:
<paste it here>Read what it builds before you run it, the same as any code you didn't write.
Step 1: of 7Set up the repo
src/
main.js entry, built as ss.js: registers components, starts the loader
loader.js finds [ss-component] roots and starts them; no component logic here
lib/ shared helpers (attribute scoping, ARIA, injected styles, language)
components/
form/ index.js + form.css
lazy-video/ index.js
dev/index.html local test page with stand-in markup for each component
test/ Vitest + jsdom tests
cloud/pages/ tiny server routes: /scripts/health, /scripts/geo
webflow/loader.js the loader that goes in the site head
vite.config.js dev server and build settings
astro.config.mjs thin hosting shell for Webflow Cloud
scripts/deploy.sh manual deploy fallbackThe code is plain JavaScript modules, one folder per component. Two tools do the work:
- Vite is a build tool. While you work, it runs a local dev server that reloads as you save. For production, it builds the bundle and the chunks.
- Vitest runs your tests. jsdom gives those tests a fake browser page, so they run without opening a real browser.
Run these in a terminal (Terminal on Mac, PowerShell on Windows). npm comes with Node.js, so install that first. <your repo> is your project's GitHub repo; if you're starting from nothing, the prompt above can scaffold one. Run them one at a time, in order. npm run dev keeps running while you work: leave it open and use a second terminal window for npm test and npm run build. If npm test stays open watching for changes, press q to quit.
git clone <your repo>
cd <your-repo-folder> # git clone makes a folder named after the repo
npm install
npm run dev # keeps running: Vite dev server with hot reload, test page at /dev/
npm test # Vitest
npm run build # the same build Webflow Cloud runsThe entry file registers every component:
// src/main.js (simplified)
import { createLoader } from './loader.js';
const modules = import.meta.glob('./components/*/index.js');
const components = Object.fromEntries(
Object.entries(modules).map(([path, load]) => [path.split('/')[2], load]),
);
if (!window.ss) {
const { init } = createLoader(components);
window.ss = { init };
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => init());
else init();
}Components are found from the folder structure, so adding a folder is all it takes to register one. Vite turns each folder into its own chunk. That is why the cost stays low: on the site we built this for, a phone-number library (about 80 kB, plus a 260 kB validation file) only downloads on pages that have a phone field.
The Vite config is short. Treat it as a starting point:
// vite.config.js (a starting point)
import { defineConfig } from 'vite';
export default defineConfig({
base: './',
publicDir: false, // public/ is the build output here, not an input
server: {
port: 5173,
strictPort: true, // fail instead of moving to another port, so ?local never points at the wrong one
origin: 'http://localhost:5173', // asset URLs resolve against the dev server
cors: { origin: /^https:\/\/[^.]+\.webflow\.io$/ }, // let your *.webflow.io staging pages load the dev build
},
build: {
outDir: 'public', // the Astro shell (step 6) serves public/ at /scripts
rollupOptions: { input: 'src/main.js', output: { entryFileNames: 'ss.js' } },
},
});The build goes into public/ because the Astro shell in step 6 serves that folder at /scripts; Vite empties it on every build, so keep nothing else there. Vite's default server.cors only allows localhost, and Vite advises against cors: true, so the config names your staging pages instead.
Step 2: of 7Add the loader
There are two loaders. The first lives in the bundle and starts components:
// src/loader.js (simplified)
export function createLoader(components) {
const started = new Map();
async function start(root) {
if (started.has(root)) return;
const load = components[root.getAttribute('ss-component')];
if (!load) return console.warn('[ss] Unknown component', root);
started.set(root, null);
try {
const mod = await load();
started.set(root, mod.init(root) || null); // init may return a cleanup function
root.setAttribute('ss-ready', '');
} catch (err) {
console.error('[ss] Component failed to start', err); // one broken component never stops the others
}
}
function init(scope = document) {
return Promise.all([...scope.querySelectorAll('[ss-component]')].map(start));
}
return { init };
}You can call init() again on a container after new markup appears; started roots are skipped. Each component starts inside its own try, so one failure never stops the others. A started element gets ss-ready, a visible hook for debugging and CSS.
The second loader is the only code that lives in Webflow:
(function () {
var local = false;
try {
local = location.hostname.endsWith('.webflow.io') &&
new URLSearchParams(location.search).has('local');
} catch (e) {}
var deployed = function () { return import(location.origin + '/scripts/ss.js'); };
if (local) {
import('http://localhost:5173/@vite/client')
.then(function () { return import('http://localhost:5173/src/main.js'); })
.catch(function () { return deployed(); }); // dev server not running: use the deployed build
} else {
deployed();
}
})();It builds the URL from location.origin, the page's own domain. A registered script is served from Webflow's CDN, so a relative path would point there instead. The local part is for testing (step 5).
Put the loader in the site head
Add it once, to the head of every page. There are two ways to do that.
The simple route (recommended if you're new to this). Paste the loader, inside a <script> tag, into Site settings → Custom code → Head code, then publish. This needs a paid Site plan or a paid Workspace. The head code field takes up to 50,000 characters, so the loader fits easily.
The API route (what we used). We registered the loader as an inline script through the Webflow Data API and applied it to the whole site's head. That keeps it versioned and out of a box several people edit. The Data API v2 custom-code endpoints only accept OAuth tokens from a Webflow App with the custom_code:write scope (and sites:write to publish); a site token won't work. It takes three calls.
These are bash commands (Mac, Linux, or Git Bash/WSL on Windows; PowerShell's quoting differs). They need jq. Keep the token in an environment variable, never in the repo.
# 1. Register the loader as an inline script (no <script> tags) and keep its id
SCRIPT_ID=$(jq -n --rawfile src webflow/loader.js \
'{sourceCode: $src, version: "1.0.0", displayName: "ComponentLoader"}' \
| curl -s -X POST "https://api.webflow.com/v2/sites/$SITE_ID/registered_scripts/inline" \
-H "Authorization: Bearer $WEBFLOW_TOKEN" -H "Content-Type: application/json" --data-binary @- \
| jq -r .id)
# 2. Apply it to the site head (uses the $SCRIPT_ID captured above)
curl -X PUT "https://api.webflow.com/v2/sites/$SITE_ID/custom_code" \
-H "Authorization: Bearer $WEBFLOW_TOKEN" \
-H "Content-Type: application/json" \
-d '{"scripts":[{"id":"'"$SCRIPT_ID"'","location":"header","version":"1.0.0"}]}'
# 3. Publish, or nothing changes on the site
curl -X POST "https://api.webflow.com/v2/sites/$SITE_ID/publish" \
-H "Authorization: Bearer $WEBFLOW_TOKEN" \
-H "Content-Type: application/json" \
-d '{"publishToWebflowSubdomain":true}'- Inline scripts are limited to 2,000 characters, which is why the loader only imports the bundle.
- Each PUT sets the whole list of applied scripts. Always include every script you want to keep, not just the new one.
- Changes need a publish, and you can publish at most once a minute. To publish to your custom domain too, add
customDomains, an array of the site's custom-domain ids, to the body. - Registered scripts can't be edited. Register a new version (1.1.0 → 1.2.0) and apply that.
Until your first deploy (step 6), publish to staging only. The loader asks for /scripts/ss.js, which doesn't exist yet. Staging still needs the loader, because the ?local test in step 5 runs through it. Until then, the browser console shows a failed import of ss.js. That's expected, and nothing on the page breaks.
Why one loader for the whole site? Pages need no code added, and a component works on any page it's dropped on. On a page with no components, the cost is one small request: ss.js, about 1.3 kB gzipped. If you trialled the loader on single pages first, remove those per-page copies before applying it site-wide, so each page loads it once.
Step 3: of 7Write your first component
The rest of this guide uses one example: a lazy-loading background video, which waits until the video is near the screen before downloading it. We picked it because it's small and shows the whole pattern end to end. The same steps work for any behaviour: forms, accordions, sliders. On the site we built this for, the first component was form validation across 7 forms.
The example uses IntersectionObserver, a browser API that tells you when an element scrolls into (or near) view.
A typical snippet, pasted into the footer code of each page that needs it. On that site it sat on 8 pages.
<script>
document.addEventListener('DOMContentLoaded', () => {
const io = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
const v = entry.target;
v.querySelectorAll('source[data-src]').forEach(s => { s.src = s.dataset.src; s.removeAttribute('data-src'); });
v.load();
v.addEventListener('canplay', () => { v.style.opacity = 1; }, { once: true });
v.play().catch(() => {});
obs.unobserve(v);
});
}, { rootMargin: '150px', threshold: 0.1 });
document.querySelectorAll('video.lazy-video').forEach(v => io.observe(v));
});
</script>The same behaviour as a component in src/components/lazy-video/.
// src/components/lazy-video/index.js (simplified)
const OPTIONS = { rootMargin: '150px', threshold: 0.1 };
// observe() and unobserve() wrap one shared IntersectionObserver that uses OPTIONS (helper not shown)
function lazy(video) {
const waiting = () => [...video.querySelectorAll('source[data-src]')];
if (!waiting().length) return null; // already loaded (e.g. by the old snippet): leave it alone
const show = () => { video.style.opacity = '1'; };
function start() {
const sources = waiting(); // check again: the old snippet may have got there first
if (!sources.length) return;
sources.forEach((s) => { s.src = s.dataset.src; s.removeAttribute('data-src'); });
video.addEventListener('canplay', show, { once: true });
video.load();
const playing = video.play();
if (playing && playing.catch) playing.catch(() => {});
}
observe(video, start); // one shared IntersectionObserver for the page
return () => { unobserve(video); video.removeEventListener('canplay', show); };
}
// ss-component="lazy-video" on the <video> or on an element around it (e.g. the Code Embed element)
export function init(root) {
const videos = root.tagName === 'VIDEO' ? [root] : [...root.querySelectorAll('video')];
const cleanups = videos.map(lazy).filter(Boolean);
return cleanups.length ? () => cleanups.forEach((c) => c()) : null;
}The behaviour is the same: same margin, threshold and fade-in. What changed:
- It exports
init(root). The loader calls it with the element that has the attribute. Every component has this shape. - It only looks inside its own root, never the whole document, and never by class.
- It returns a cleanup function and shares one observer across the page.
- It can run next to the old snippet. It checks for waiting sources at the start and again at the moment of loading (step 5 explains why).
The file is under 1 kB.
Rules that apply to every component
Select by attribute, never by class or id. Designers rename classes, and Webflow can repeat ids: on that site, three forms on one page shared an id. Attributes are a stable contract. If you need ids for ARIA links, generate unique ones in the component.
Scope attribute names to the component. Use ss-component="<name>" for the root, ss-<name>-el="<role>" for parts inside it, and ss-<name>-<setting> for options. Then different components never pick up each other's elements, even when nested. A short prefix reads better in the Designer than data-. A small helper keeps components honest:
// src/lib/attrs.js (simplified)
export function scope(root, name) {
const role = `ss-${name}-el`;
return {
el: (value) => root.querySelector(`[${role}="${value}"]`),
els: (value) => [...root.querySelectorAll(`[${role}="${value}"]`)],
setting: (node, key, fallback = null) => node.getAttribute(`ss-${name}-${key}`) ?? fallback,
};
}Ship the component's CSS inside the component. Webflow's per-page CSS drops classes that no Designer element uses. So inject component styles at runtime, scoped with attribute selectors. Use logical properties such as margin-inline-start and text-align: start, so right-to-left (Arabic) pages mirror without extra code.
Never break native Webflow. Add to Webflow's behaviour, don't replace it. Our form component turns off browser validation only once it has started, so if the script fails, the browser's own checks still work.
Step 4: of 7Add the attribute in Webflow
In the Designer, select the element, open the Element settings panel → Custom attributes and click +. Add ss-component with the value lazy-video.
For the video example, the attribute goes on the Code Embed element that holds the video, and the component handles every video inside it. There is a practical reason. The Webflow API refuses to read or write embed code that contains CMS bindings, so editing the embed code itself is often not an option. An attribute on the Code Embed element is something any editor can add in the Designer without touching code.
Don't remove the old snippet yet. Leave it on the page until step 7; the component is built to run alongside it, and step 5 shows how to test that.
Step 5: of 7Test it, locally and on staging
On staging with ?local
This is the most useful part of the setup: your local code, running on the real staging site, with nothing deployed.
- Run
npm run dev. - Open any staging page with
?localin the URL. - That page load imports the scripts from your dev server, with hot reload.
Every other visitor, and any URL without ?local, gets the deployed build. Production domains ignore the flag. If your live site has no custom domain and runs on *.webflow.io, ?local works there too; it only ever loads from the visitor's own machine.
If it doesn't load:
- No changes showing? The page is on the deployed build. Check that the dev server is on port 5173 and that
vite.config.jsallows your staging address (the config in step 1 sets both; Vite's default CORS only allows localhost). - Chrome asks to access the local network the first time. Nothing loads until you allow it.
- Dev server not running? The loader quietly uses the deployed build.
- Not sure which build is running? Have the loader log a line to the console in each branch (the prompt asks for this).
What to test
"Do a lot of tests so we don't ship bugs" was an explicit requirement on that project. This is what it taught us.
- Write unit tests in jsdom. For the video, that meant a fake IntersectionObserver and stubbed
load()andplay(). Cover the cases that matter: nothing loads before the video is in view, it loads once, the fade-in timing, a blocked autoplay, browsers without IntersectionObserver, cleanup, the wrapper case and the loader integration. - Test your tests. Break the component on purpose (wrong margin, a removed guard, a skipped in-view check, only the first video handled) and confirm a test fails each time. One of our breaks wasn't caught at first, so we tightened that test.
- Check it in a real browser. The dev page at
/dev/has stand-in markup. We used a generated 3-second test video (made with ffmpeg) to prove nothing downloads before scrolling, then that it loads, fades in and plays. - Test on real pages, even before changing Webflow. With
?local, we cloned each real video in the browser console with its sources reset, added the attribute and started the local build. Then we scrolled to each one and checked it loaded, faded in and played with no console errors. - Run the same checks against the old snippet. These control runs tell you whether a difference comes from your code or was already there.
- Test that your component and the old snippet can run together. During a migration, a page can briefly have both. A control run exposed exactly this for us: the old snippet loaded the video first, then the component set the sources from a
data-srcthat no longer existed. They became the string "undefined" and the video broke. The fix was to check again at the moment of loading, not only at start. Now our test runs both on the same videos and checks each loads exactly once. - Check the site's real edge cases. A video in a hidden tab should load when the tab is clicked, as before. Videos already on screen at load should start immediately.
Step 6: of 7Deploy
Every change goes through a pull request: a proposed change on its own branch that someone reviews before it is merged into main.
- Branch from main:
feature/<name>orfix/<name>. One component or bug per pull request. - Run the tests and the build, and check on staging with
?local. - Open the pull request: what changed, which pages are affected, how it was tested. Merge after review.
- Deploy, then check
/scripts/health, which returns the deployed version.
Hosting on Webflow Cloud. Webflow Cloud only builds Astro and Next.js apps, and this is a plain Vite build. The workaround is a thin Astro shell whose config runs the Vite build first and drops the output into public/. Astro then serves it under /scripts.
// astro.config.mjs (a starting point)
import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare'; // optional: Webflow Cloud adds an adapter if you don't declare one
import { build } from 'vite';
const viteScripts = {
name: 'vite-scripts',
hooks: {
'astro:config:setup': async ({ command }) => {
if (command === 'build') await build({ configFile: './vite.config.js' }); // writes ss.js and its chunks to public/
},
},
};
// No base or build.assetsPrefix: Webflow Cloud sets both from the mount path (/scripts)
export default defineConfig({
srcDir: './cloud', // server routes in cloud/pages, outside the Vite src/ folder
output: 'server',
adapter: cloudflare(),
integrations: [viteScripts],
});Don't set Astro's base or build.assetsPrefix. Webflow Cloud sets both at build time from your environment's mount path, and overwrites whatever you commit. srcDir keeps the server routes in cloud/, outside the Vite src/ folder. The @astrojs/cloudflare adapter is optional: if you don't declare one, Webflow Cloud installs one. A webflow.json at the repo root, {"cloud":{"framework":"astro"}}, tells Webflow Cloud which framework it is building.
Chunks use a relative base, so the same build works on staging and production. Webflow Cloud serves files with Cache-Control: private, no-cache, so a deploy is live immediately and browsers revalidate ss.js and its chunks on each load.
Link the repo to Webflow Cloud
- In the Webflow dashboard, create a Cloud app.
- Authorise GitHub and install the Webflow Cloud GitHub App.
- Bring your own repo, and choose your existing site.
- Create an environment: pick a branch (main) and the mount path
/scripts.
From then on, every push to that branch deploys. A Cloud route overrides a Webflow page at the same path, so don't use /scripts for a page.
To deploy by hand, use the Webflow CLI (@webflow/webflow-cli, which needs Node 22.13 or later) from an up-to-date main:
npm install --save-dev --save-exact @webflow/webflow-cli # pinned, see below
npx webflow auth login
npx webflow cloud init --mount /scripts --framework astro
npx webflow cloud deployNewer versions of the CLI rename these commands to webflow apps …, so check npx webflow --help for the version you pinned.
Without Webflow Cloud
Host the build on any HTTPS server you control, and keep the same inline loader, pointing its import at that server's ss.js. Don't register ss.js itself as a hosted script: a hosted script is pinned to an integrity hash, which would change on every deploy. If the server is on another domain, it must send CORS headers that allow your site, because module imports are cross-origin.
Pin your tools. A pre-release version of the deploy CLI once exited with no output and no error, so our deploy script ran the tests and then deployed nothing. Pin exact versions, and always check the deployment status afterwards.
Step 7: of 7Remove the old snippet, one page at a time
Only now, with the component deployed, go back to Webflow:
- On one page, make sure the attribute is in place.
- Remove the old
<script>block from that page's custom code. - Publish that one page, and check it.
- Move on to the next page.
Why this order? If you add the attribute and remove the snippet before the component is deployed, a publish by anyone leaves the page with neither. In the video example, the videos would stay invisible, because they start at opacity 0.
Why one page per publish? A problem stays on one page, and rollback is small: revert the pull request, or put the snippet back. A full site publish also ships everyone's pending changes, so agree one with your team first.
If you script this through the API, remember that each PUT to a page's or the site's custom_code sets the whole list of applied scripts. Send every script you want to keep, and change one at a time.
After each publish, check more than the component. We confirmed every published page had exactly one loader and its other critical scripts, and that every form still started and blocked an empty submit.
Other things that will catch you out
Pin your libraries. Unversioned CDN links and @latest packages let someone else change your live site. Install dependencies from npm with exact versions and bundle them.
Webflow's form collector picks up any input. A search box in a phone country picker, inside a form, was submitted as an extra "Field N". Render dropdowns like that in <body>, outside the form.
Visitor country on Webflow Cloud. Webflow's proxy sits between the visitor and your app, so request.cf.country gives the proxy's country, not the visitor's. Read the x-wf-geo-country header instead.
Vite's dependency cache. After a production build, the dev server can serve a stale optimised dependency, which shows up as a 504 on that file. Restart the dev server; if it keeps happening, run vite --force once.
What this gave us
- 7 formsForm validation is live on all 7 visitor forms on staging, as one component.
- 8 → 1The lazy-video component replaced a snippet copied onto 8 pages.
- 1.3 kB
ss.jsis about 2.6 kB, or 1.3 kB gzipped. Component code only downloads where it's used.
Your next component
Once the first component is in, the next one is just a new folder. On that site, the audit gave a ranked list: an accordion, the related-news slider (bundling the slider library once), a gallery slider, a sticky project bar, and finally the scroll-driven sequence animation, about 69 kB of near-duplicate code today. Each one moves the same way: one component per pull request, one page at a time.
You don't need to fix everything at once. Pick one snippet and start there.
FAQ
Where does custom code go in Webflow?
In three places: site settings, where the head code field runs on every page; page settings (one page); and Code Embed elements (one spot on a page). That works for one snippet. Once the same code is copied onto several pages, move it into a repo as a component and start it with a custom attribute, as this guide shows. Developers have a fourth place: scripts registered through the Data API by a Webflow App and applied to the site or a page. This guide's loader goes in the head code field or, through the API, in a registered script.
How do I make custom JavaScript move with a Webflow component?
Put the code in a repo as a component, and give the Webflow element a custom attribute such as ss-component="lazy-video". A loader in the site head finds every element with that attribute and starts its code. Copy the element to another page and the behaviour comes with it.
What is a custom attribute in Webflow?
A name and value you add to an element in the Designer, under Element settings → Custom attributes. Scripts can find elements by it. Unlike classes, which designers rename, and ids, which Webflow can repeat, an attribute you add for code stays stable.
Do I need to know Vite or Vitest to do this?
No. Vite builds your code and runs a dev server; Vitest runs your tests. Day to day you use four commands: npm install, npm run dev, npm test and npm run build.
How do I test a script on my Webflow staging site without deploying?
Have the loader check for a ?local flag on staging only. With the flag, that page load imports scripts from your local dev server, with hot reload. Everyone else gets the deployed build, production ignores the flag, and if the dev server isn't running the loader falls back to the deployed build.
Why does my script's CSS disappear on some Webflow pages?
Webflow's per-page CSS drops classes that no Designer element on that page uses. If your script adds classes the Designer never placed, their styles can be missing. Ship the CSS inside the component, inject it at runtime and scope it with attribute selectors.
Will a site-wide loader slow down pages with no components?
Very little. On a page with no components, the cost is one small request: ss.js, about 1.3 kB gzipped. Component code is split into chunks that only download on pages that use them.