A small JavaScript change can alter a headline, hide a field, or move a visitor toward a different conversion path. A careless script can also break the page.
JavaScript A/B testing in Mida.so gives you a controlled way to deploy custom variations without changing the control version. Mida handles the test setup and traffic assignment. Your code handles the page change. The quality of that code determines whether the test produces useful data or confusing results.
Key Takeaways
- Use Mida’s control and variation structure instead of building visitor assignment with
Math.random(). - Run custom code after the DOM is ready and check that target elements exist.
- Use stable selectors and an idempotent function that won’t apply the change twice.
- Test every variation in preview and QA before publishing it to production.
- Configure the conversion goal in Mida before reading the test result.
Set Up the Mida.so A/B Test First
Start with the test question. A useful question connects one page change to one measurable action.
For example:
Does changing the pricing-page CTA from “Request a demo” to “Start your free trial” increase trial sign-ups?
The original page is the control. The modified page is the variation. Keep the control unchanged. Add custom JavaScript only to the variation that needs the change.
After the Mida.so platform is installed on your website, create an A/B test in the Mida dashboard. Select the page or URL rule where the test should run. Add the control and variation, then configure the audience and traffic allocation available in your workspace.
Use the variation’s custom JavaScript area for changes that need more control than a visual editor provides. This is useful for:
- Replacing text or links
- Adding or removing classes
- Showing a different content block
- Changing form behavior
- Testing a different navigation path
- Applying a variation to elements rendered by a front-end framework
Mida should assign visitors to the control or variation. Don’t add your own random split inside the script. If both systems assign traffic independently, visitors can receive inconsistent experiences and the reporting becomes unreliable.
Keep one test responsible for one main change. If the script changes the headline, CTA, form layout, and navigation at the same time, you won’t know which change affected the result.
Use Production-Safe JavaScript Patterns
Custom test code often fails for simple reasons. The script runs before the target element exists. The selector changes after a deployment. A page transition runs the function again and duplicates the change.
Use four basic protections:
- Wait for DOM readiness.
- Return safely when an element is missing.
- Target stable attributes or IDs.
- Mark the element after the variation has been applied.
The following example changes a pricing CTA. It works when the element is available at page load and when a client-rendered page adds it later.
(function () {
"use strict";
var selector = '[data-mida-cta="primary"], #pricing-cta';
function applyVariation() {
var cta = document.querySelector(selector);
if (!cta || cta.dataset.midaVariantApplied === "true") {
return Boolean(cta);
}
cta.dataset.midaVariantApplied = "true";
cta.textContent = "Start your free trial";
cta.setAttribute("data-mida-variant", "trial-cta");
cta.classList.add("mida-cta-variation");
return true;
}
function start() {
if (applyVariation()) {
return;
}
if (!window.MutationObserver || !document.body) {
return;
}
var observer = new MutationObserver(function () {
if (applyVariation()) {
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
window.setTimeout(function () {
observer.disconnect();
}, 10000);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", start, { once: true });
} else {
start();
}
}());
The DOMContentLoaded event prevents the first query from running too early. The null check prevents an error on pages without the CTA.
The selector uses a custom data attribute and an ID fallback. A data attribute such as data-mida-cta="primary" is more reliable than a generated CSS class or a selector based on element position. Avoid selectors such as .button:nth-child(2). A small layout change can make that selector target the wrong element.
The data-mida-variant attribute helps you confirm the variation in DevTools. The midaVariantApplied flag makes the function idempotent. If Mida, a route change, or a framework re-render invokes the code again, the CTA won’t receive the change twice.
You can review other selector methods in the MDN querySelector reference.
Build a Variation That Changes More Than Text
Text replacement is a good first test because it has a small surface area. JavaScript can also combine several controlled changes inside one variation.
Suppose the control contains a secondary navigation link that distracts visitors from the main signup action. The variation can hide that link and add a class to the primary section.
(function () {
"use strict";
function applyVariation() {
var section = document.querySelector('[data-mida-section="signup"]');
var secondaryLink = document.querySelector('[data-mida-link="secondary"]');
if (!section || section.dataset.midaApplied === "true") {
return Boolean(section);
}
section.dataset.midaApplied = "true";
section.classList.add("mida-signup-variation");
if (secondaryLink) {
secondaryLink.hidden = true;
}
return true;
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", applyVariation, { once: true });
} else {
applyVariation();
}
}());
This script doesn’t assume the secondary link exists. The section is required because it identifies the variation target. The link is optional, so the script continues when that element isn’t present.
Keep layout styling in your site’s CSS or in the CSS area provided by your testing setup. JavaScript should change the content or state. CSS should control spacing, color, display, and responsive behavior. That separation makes the test easier to remove after it ends.
Be careful when changing links. Updating an href can affect the conversion path, analytics parameters, accessibility expectations, and browser history. If the test needs a different destination, confirm the URL and tracking requirements with the team that owns the page.
Don’t attach a new click listener every time the script runs. If you need custom interaction logic, use a data flag or event delegation. Also check Mida’s current documentation before calling any tracking API. A guessed event name can create misleading data.
Validate the Code Before You Publish
Never move custom JavaScript directly from an editor into a live test without checking it. Use Mida’s preview tools first, then run the variation in a QA environment that matches production.
Start with the normal page load. Confirm that the control has no unexpected changes and that the variation changes only the intended element.
Test the page in these conditions:
- A fresh browser session
- A returning visitor
- Mobile and desktop viewport sizes
- A slow network connection
- A page where the target is rendered after load
- A page where the target doesn’t exist
- A client-side route change, if the site is an SPA
Open DevTools and check the console. A variation that looks correct can still throw an error on another template. Inspect the target element and confirm that the expected class and data attributes appear once.
Check for flicker as well. If the original CTA appears before the variation changes it, visitors may see two versions during page load. That can affect perception and interaction data. Reduce the delay by loading Mida as required by its installation instructions and keeping the variation code short.
Use the browser’s network panel to confirm that the page loads the Mida script and that the test is active in the intended environment. Don’t publish a test until the control and variation are both accessible through the correct URL rule.
Use MutationObserver guidance from MDN when you need to support content that appears after the initial page load. Disconnect the observer after the target is found. A permanent observer adds work to every later DOM mutation.
Preview catches syntax and targeting problems. QA catches page, browser, and deployment problems. Use both.
Configure Goals and Read the Result
The JavaScript changes the experience. Mida’s configured goal determines what counts as a conversion.
Choose one primary goal before starting the test. For a pricing CTA, that might be a completed signup, a qualified demo request, or a checkout start. Avoid switching the primary goal after visitors have entered the test. That makes the result harder to interpret.
Secondary metrics can provide context. Track form starts, CTA clicks, checkout errors, or navigation depth when those metrics are available in your Mida setup. Treat them as supporting evidence. A higher click rate doesn’t prove that the variation improved revenue if completed sign-ups declined.
Give the test enough exposure to capture normal traffic patterns. Don’t stop the test because of a strong result after a short burst of visitors. Check the test across weekdays, weekends, traffic sources, devices, and relevant audience segments.
When the test ends, remove the temporary code or promote the winning implementation into the main site codebase. Test cleanup matters. Old experiment scripts can conflict with later tests and leave visitors with outdated content.
Fix Common JavaScript A/B Testing Failures
A blank result usually starts with targeting. The script may run on the wrong URL, or the selector may not match the production markup. Copy the selector from the live DOM and confirm the test’s page rule.
A variation that appears twice usually lacks an idempotency check. Add a data attribute, class check, or equivalent guard before changing the element.
A variation that works on refresh but not during navigation needs SPA handling. The page may update its content without reloading the document. Use a supported route-change hook or a short, bounded MutationObserver pattern. Don’t run an unrestricted polling loop.
A test that records clicks but not completed conversions usually has a goal or event configuration problem. Review the goal in Mida before changing the JavaScript. Don’t hide the error by adding unverified tracking calls.
If a site redesign changes the CTA markup, pause the test and update the selector in QA. A variation should not silently target a different element after a deployment.
Conclusion
Mida.so handles the A/B test structure, while your JavaScript controls the variation. Keep the control untouched, use stable selectors, wait for the DOM, and make every change safe to run more than once.
Validate the script in preview and QA before publishing. A short, well-targeted variation produces cleaner data than a large script that changes several parts of the page. Reliable JavaScript A/B testing starts with code that fails safely.
