This code is a JavaScript implementation for running A/B tests on a web page and tracking user interactions. It allows you to serve different variants of content to users and record statistics about how they interact with the variations.
🔗 Code Organization
The code is structured into functions and event listeners that are triggered at various points in the user's interaction with the web page.
🛠️ Functions
-
getDeviceId()
: Retrieves or generates a unique device ID and stores it in local storage. -
getRandomVariant(test_id)
: Fetches a random test variant from a remote server using the device ID. -
setNewContent(selector, variant, variant_a, variant_b)
: Updates the content of an HTML element specified by a selector with a new variant. -
runTests()
: Orchestrates the A/B testing process. It fetches tests, selects variants, and tracks user interactions. -
getTests()
: Retrieves the available tests for the current page from the remote server. -
runClickTest(test, event, variant)
: Listens for click events on specified elements and updates event statistics. -
updateEventStatistics(event_type, event_id, test_id, variant)
: Sends statistics about user interactions to the server. -
runViewTest(test, event, variant)
: Handles view events and sends event statistics to the server. -
Event listener: The script starts running the tests when the DOM content is fully loaded.
📡 API Integration
The code interacts with a remote API hosted at https://api.keak.com
. It uses this API to fetch tests, variants, and record event statistics.
-
Include this JavaScript file in your web project.
-
Ensure the
HOST
variable is set to the correct API endpoint. -
Implement server-side logic to define A/B tests and their variations on the backend. These tests should be accessible via the API.
-
Add test-specific data attributes to your HTML elements that you want to vary based on A/B tests. Define these data attributes in your server-side code.
-
In the code, specify the element selectors, variant IDs, and event types that should trigger A/B testing.
-
Customize the statistics update frequency (currently set to 5000 milliseconds) in the
updateEventStatistics
function as needed.
🤝 Contributing
Contributions to this project are welcome! To contribute:
-
Fork the repository.
-
Make your changes and improvements.
-
Create a pull request with a clear description of your changes.
-
Be sure to follow best practices and maintain code quality.
-
Provide appropriate documentation and comments for your changes.
-
Collaborate with the community for code review and improvements.