Skip to main content
How to Add RB2B's Script to Typescript
Updated over 6 months ago

This guide will help you install the RB2B tracking script on a TypeScript website, ensuring the script is properly integrated and functioning. Follow the steps below to convert and implement the provided JavaScript snippet into TypeScript.

Copy the RB2B Script

Start by ensuring that you have the RB2B script ready. You can find it in the Script section of the dashboard. Copy the entire code snippet to your clipboard, preparing it for embedding into your Typescript site.

Convert JavaScript to TypeScript

To integrate the script into a TypeScript environment, follow these modifications as shown in the example below:

  1. Function Declaration and Invocation: Use the IIFE syntax for TypeScript.

  2. Variable Assignment: Split the assignment of window.reb2b and var reb2b.

  3. Type Annotations: Add TypeScript type annotations for function parameters.

  4. Error Handling: Ensure first.parentNode is not null before inserting the script.

Reformatted Snippet for Typescript

(function () {
var reb2b = window.reb2b || [];
window.reb2b = reb2b;
if (reb2b.invoked) return;
reb2b.invoked = true;
reb2b.methods = ["identify", "collect"];
reb2b.factory = function (method: string) {
return function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(method);
reb2b.push(args);
return reb2b;
};
};
for (var i = 0; i < reb2b.methods.length; i++) {
var key = reb2b.methods[i];
reb2b[key] = reb2b.factory(key);
}
reb2b.load = function (key: string) {
var script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.src = "https://s3-us-west-2.amazonaws.com/b2bjsstore/b/" + key + "/reb2b.js.gz";
var first = document.getElementsByTagName("script")[0];
if (first && first.parentNode) {
first.parentNode.insertBefore(script, first);
}
};
reb2b.SNIPPET_VERSION = "1.0.1";
reb2b.load("YOUR-UNIQUE-ID");
})();

Integration into Your TypeScript Project

  1. Create a New File: Create a new TypeScript file, for example, reb2b.ts, in your project.

  2. Add the Script: Copy the TypeScript version of the script into reb2b.ts.

  3. Replace YOUR-UNIQUE-ID: Replace "YOUR-UNIQUE-ID" with your actual unique ID provided by RB2B.

  4. Compile the TypeScript File: Ensure your TypeScript project is set up to compile TypeScript files into JavaScript. This usually involves running tsc (TypeScript compiler) or using a build tool like Webpack.

  5. Include the Compiled Script: Include the compiled JavaScript file in your HTML or web application. For example, if it compiles to reb2b.js:

<script src="path/to/reb2b.js"></script>

By following these steps, you will successfully integrate the RB2B tracking script into your TypeScript website. This ensures that your tracking and user identification processes are seamlessly incorporated, leveraging the benefits of TypeScript for better maintainability and error checking.

Did this answer your question?