In the world of web performance, every kilobyte counts. Modern websites often rely on sophisticated analytics and A/B testing frameworks to understand user behavior and optimize conversions. However, this power comes at a cost: large, monolithic JavaScript files bloated with code for every conceivable experiment and tracking event. This one-size-fits-all approach slows down your site for every user, even those not part of a specific test.
What if you could ditch the monolithic script and instead generate a lean, purpose-built JavaScript file for each user on the fly? Imagine delivering only the code needed for that user's specific segment and active A/B tests. This is the power of dynamic script generation, and with esbuild.do, it's easier to implement than ever before.
Traditionally, implementing analytics or A/B testing involves including a static script tag in your HTML. This script contains the logic for all active and potential experiments.
This leads to several issues:
The solution is to move the decision-making logic from the client to the server. Your server already knows who the user is, what segment they belong to, and which A/B tests they should see. It can use this information to assemble a customized script containing only the necessary code.
This is where esbuild.do shines. As a blazing-fast JavaScript bundling and minification API, it allows you to harness the power of esbuild without any local setup. You can send multiple TypeScript or JavaScript code snippets to the API and receive a single, minified, browser-ready file in milliseconds.
Let's build a dynamic tracking script for an e-commerce site. We want to:
First, we'll break our logic into small, focused TypeScript files. This keeps our codebase clean and maintainable.
analytics/base.ts:
// Shared analytics functions
export function trackEvent(name: string, props: Record<string, any>) {
console.log(`EVENT: ${name}`, props);
// Your real analytics provider call (e.g., window.analytics.track)
}
analytics/guest-events.ts:
import { trackEvent } from './base';
// Specific events for guests
trackEvent('guest_page_view', { path: window.location.pathname });
analytics/user-events.ts:
import { trackEvent } from './base';
// Specific events for authenticated users
const userId = (window as any).CURRENT_USER_ID;
trackEvent('user_page_view', { path: window.location.pathname, userId });
ab-tests/buy-button-new.ts:
// Logic for the new A/B test variant
console.log('A/B Test: New Buy Button variant is active.');
const buyButton = document.getElementById('buy-button');
if (buyButton) {
buyButton.style.backgroundColor = 'green';
buyButton.innerText = 'Buy It Now!';
}
Next, in your server-side code (e.g., a Node.js/Express endpoint), you'll determine which files to include based on the user's session.
// In your server (e.g., Express.js route)
import { doing } from '@do-inc/sdk';
import fs from 'fs/promises';
app.get('/dynamic-tracker.js', async (req, res) => {
// 1. Determine user context
const user = getUserFromSession(req); // Your auth logic
const userIsInTest = isUserInABTest(user); // Your A/B test logic
// 2. Prepare the source files and entry points for esbuild.do
const sourceFiles = {
'analytics/base.ts': await fs.readFile('analytics/base.ts', 'utf-8'),
'analytics/user-events.ts': await fs.readFile('analytics/user-events.ts', 'utf-8'),
'analytics/guest-events.ts': await fs.readFile('analytics/guest-events.ts', 'utf-8'),
'ab-tests/buy-button-new.ts': await fs.readFile('ab-tests/buy-button-new.ts', 'utf-8')
};
const entryPoints = user ? ['analytics/user-events.ts'] : ['analytics/guest-events.ts'];
if (userIsInTest) {
entryPoints.push('ab-tests/buy-button-new.ts');
}
// 3. Call the esbuild.do agentic workflow
const { bundledCode } = await doing.esbuild({
entryPoints,
sourceFiles,
bundle: true,
minify: true,
platform: 'browser',
format: 'iife' // Immediately Invoked Function Expression for browsers
});
// 4. Serve the dynamically generated script
res.type('application/javascript').send(bundledCode);
});
Finally, replace your static script tag with a single, dynamic one.
<script src="/dynamic-tracker.js" async defer></script>
That's it! A guest user will receive a tiny script with just the guest tracking logic. A logged-in user who is part of the A/B test will receive a script that includes their specific tracking events and the buy button modification logic. All other users get a script tailored perfectly to their context.
By adopting this dynamic approach with esbuild.do, you achieve:
Ready to supercharge your site's performance and streamline your experimentation workflow? Stop sending bloated JavaScript to your users.
Visit esbuild.do to see how easy on-demand bundling can be.