Web - JavaScript
Obtain an Environment ID for Installation
Sprig provides two environments (with corresponding ENVIRONMENT_IDs). The Development environment behaves differently than Production. It does not adhere to the resurvey waiting period policy, allowing a user event to trigger a study repeatedly. This makes verifying your installation and conducting tests easier, so the Development environment is recommended for these purposes. Then, you can use the Production environment to deploy your studies to receive user feedback.
Depending on your current environment, replace ENVIRONMENT_ID during installation with the Production ID or Development ID by clicking Get Code on Connect > JavaScript.
Installation Options
You can install Sprig with an HTML code snippet. The HTML installation method automatically ensures you have the latest version of our SDKs.
In addition you can install Sprig with NPM, or YARN.
Install with HTML
Add the following JavaScript snippet to your webpage to complete a Sprig JavaScript SDK installation. Add the snippet to every page on your website where you want Sprig to track your users. You can paste the snippet anywhere on the page, but preferably at the bottom of the document, before the </body>
tag.
With this installation method, the latest version of the SDK will be fetched asynchronously when the page is loaded and then become accessible.
<script>
(function(l,e,a,p) {
if (window.Sprig) return;
window.Sprig = function(){S._queue.push(arguments)}
var S = window.Sprig;S.appId = a;S._queue = [];window.UserLeap=S;
a=l.createElement('script');
a.async=1;a.src=e+'?id='+S.appId;
p=l.getElementsByTagName('script')[0];
p.parentNode.insertBefore(a, p);
})(document, 'https://cdn.sprig.com/shim.js', 'ENVIRONMENT_ID');
</script>
Install with NPM/Yarn
Use the following shell command to install the Sprig SDK through NPM or Yarn as part of your web application.
You have to update the SDK manually to receive the latest functionality. We recommend you update the package weekly for improved functionality and bug fixes. With this installation method, Sprig will be bundled with the rest of your front-end application and be immediately accessible on page load.
npm install --save @sprig-technologies/sprig-browser
yarn upgrade @sprig-technologies/sprig-browser --latest
Then, in your application, initialize Sprig with your ENVIRONMENT_ID:
import { sprig } from '@sprig-technologies/sprig-browser';
export const Sprig = sprig.configure({
environmentId: 'ENVIRONMENT_ID',
})
Other parameters for configure
are listed below, in the section Customize Appearance.
Command to update the Sprig SDK
When using NPM or YARN, in order to keep your Sprig installation updated with the latest features run the following command:
npm update @sprig-technologies/sprig-browser
yarn update @sprig-technologies/sprig-browser
CSP Configuration
Using Sprig for Web studies may require you to update your web application's Content Security Policy (CSP). This may be required because Sprig uses third-party libraries to support JavaScript.
The following list of sources is required to use Video & Voice questions:
- Base64 SVGs and fonts.
- Connecting to Mux (for streaming and short video uploads).
- Connecting to Google APIs (for long video uploads).
Examples are shown in the following CSP source list:
<meta
http-equiv="Content-Security-Policy"
connect-src blob: data: https://api.sprig.com https://cdn.sprig.com;
font-src data:;
worker-src blob:;"
/>
<meta
http-equiv="Content-Security-Policy"
content="img-src data: https://*.mux.com;
connect-src blob: data: https://api.sprig.com https://*.mux.com https://storage.googleapis.com https://cdn.sprig.com https://cdn.userleap.com;
font-src data:;
media-src blob: https://*.mux.com;
worker-src blob:;"
/>
Info
As every company has different security policies, the example may not reflect the complete configuration. You may need to add additional keys and values in order to comply with your own organization’s policies.
Verify Installation
There are two primary ways to verify the installation is working as intended: viewing People in the Sprig app or opening the browser's JavaScript console for the page in question and running a command.
People Page
Navigate to People to verify that your site sends events to Sprig. When a user visits your site, they will appear in this view. Their study eligibility or Study Status will also be shown. If you have set the EMAIL_ADDRESS attribute, it will also be displayed.
Browser Console
In Sprig, only users who match a running study's specific targeting will ever see a study due to the JavaScript. This can make it challenging to test out how to study will look for users on your site.
In addition to the Live Preview rendered during the Design and Launch of a given study in the Dashboard, you can also manually view and test a study from your site by running the following command in the browser JavaScript console.
- In the Sprig app go to Settings > Configure.
- Select Allow Manual Study Display.
- In your browser, open the JavaScript console.
- Run the command:
Sprig('displaySurvey', SURVEY_ID);
To find the SURVEY_ID, go to Studies and then click on a study. The SURVEY_ID is the integer at the end of the PATH of the URL in your browser.
https://app.sprig.com/surveys/SURVEY_ID
. Make sure the Study is in the same Environment as the browser console. - If the Sprig snippet is already installed on that page, your browser will display the study.
- If the questions are not rendering correctly or responses aren't uploaded, check your browser console for any errors. You may have to work with your engineering and security teams to, for example, update your website's CSP settings to resolve the errors.
Testing a study in this manner will record responses, and your production environment will honor the recontact waiting period before tracked events for the same user will trigger another study.
After you have finished your testing, consider returning to Settings > Configure and select Disable Manual Study Display. This will prevent any other visitor from using displaySurvey
in your environment.
Identify Users
Sprig allows you to differentiate users by setting a USER_ID. While setting USER_IDs is optional, it helps provide a consistent experience across platforms and prevents users from seeing the same study multiple times. It also helps you to optimize the number of events you send to Sprig. The user identifier should be unique and associated with a user in some way.
This user identifier is stored via local storage, and this function can be called multiple times safely. We recommend you set the user identifier every time you initialize Sprig and when your user logs in.
Set the USER_ID after the installation snippet if they are already logged in or after the user logs in to your website. You can also provide Sprig with the user's email address. It is not required for web and mobile studies but is required to enable email-based studies.
// import the client returned from your Sprig.configure call
import { Sprig } from 'utils/sprig'
Sprig.setUserId('USER_ID');
Sprig.setEmail('EMAIL_ADDRESS');
<script>
Sprig('setUserId', 'USER_ID');
Sprig('setEmail', 'EMAIL_ADDRESS');
</script>
Logout
When a user logs out of your webpage, make sure to log out of Sprig. This will prevent new activity from being associated with the incorrect user.
// import the client returned from your Sprig.configure call
import { Sprig } from 'utils/sprig'
Sprig.logoutUser();
<script>
Sprig('logoutUser');
</script>
Set Visitor Attributes
Sprig lets you build up user profiles to provide more context to understand the user's feedback better. Sprig tracks a default set of attributes and allows you to specify custom attributes and values specific to your business.
You can use visitor attributes for study targeting to help refine the cohort of users you wish to survey. They can also be used as filters to drill into the study response data in the Sprig Dashboard.
Default Attributes
Sprig's JavaScript snippet automatically tracks and attaches the following attributes:
- Browser and version
- Device
- Session count
- Page URL
- Screen size
- Browser Language
- Operating System and Version
Info
Sprig only supports in-product targeting for browser language. You can access the other attribute data through data export.
Custom Attributes
Optionally, you can send in custom attributes about the visitor. This information is visible on the People section of the Sprig Dashboard when viewing a Visitor.
Values
ATTRIBUTE
{String} required - the attribute name to set. Attributes beginning with ! are reservedVALUE
{Object} required - the value to set for the specified attribute name (typically a string or number, but anything convertible to JSON will work)
// import the client returned from your Sprig.configure call
import { Sprig } from 'utils/sprig'
Sprig.setAttribute('ATTRIBUTE', 'VALUE');
// for multiple attributes
// saves multiple round-trips and reduces data usage
Sprig.setAttributes({
ATTRIBUTE1: 'VALUE1',
ATTRIBUTE2: 'VALUE2'
});
// if attributes no longer apply to the user,
// you can delete multiple at a time
Sprig.removeAttributes(['ATTRIBUTE1', 'ATTRIBUTE2']);
<script>
// for a single attribute
Sprig('setAttribute', ATTRIBUTE, VALUE);
// for multiple attributes
// saves multiple round-trips and reduces data usage
Sprig('setAttributes',{
ATTRIBUTE1: VALUE1,
ATTRIBUTE2: VALUE2
});
// if attributes no longer apply to the user,
// you can delete multiple at a time
Sprig('removeAttributes', [ATTRIBUTE1, ATTRIBUTE2]);
</script>
Some common attributes to set are:
- Location
- Referral URL
- A/B test group
Track Events to Display Studies
Sprig provides two types of Events for triggering and filtering your studies using our SDK, No-Code and Code events.
Code Events
To add or track a Code event for triggering or filtering, you will need the following snippet. If you or your colleague added a Code event via the UI, be sure that the event name used in the UI is identical to the name used in this snippet. You can also optionally add properties to your event.
// import the client returned from your Sprig.configure call
import { Sprig } from 'utils/sprig'
Sprig.track('EVENT_NAME', {property1: 'value'});
<script>
Sprig('track', 'EVENT_NAME');
</script>
When Sprig receives this event, the study is displayed if the user is eligible to receive that study. You can see the overall eligibility of a given user on the People page, though studies may have individual filters.
Info
The
track
function makes a network call, so be sure to give it enough time to complete. Also, note that if you or your colleague added a Code event to the UI via the Code option there, the name used in the code would need to match the name in the UI exactly.
No-Code Events
There are three types of No-Code events: Page URL, Inner Text, and CSS Selector. No-code events can only be used to trigger web studies, not filter them. Once Sprig is installed, no-code events permit study designers to create triggers without changing the application, potentially not requiring engineering support.
Page URLs
Page URL events define a single page or a set of pages to trigger a study. Sprig supports Regular Expressions, which can be useful to include or exclude groups of pages.
Inner Text
This event is invoked when a user clicks one or more HTML elements, with some specific inner text, or rendered text, found on one or more pages. The snippet needs to be installed and configured. Once configured, they are viewed on the Events page.
CSS
This event is invoked when a user clicks a specific CSS class.
Customize Appearance
You can set a hard limit on the height of your study with the maxHeight
parameter, which sets the maxHeight
property of the iframe.
For custom installations, if Sprig is installed within an iframe that initially has 0 width, by default, studies will render with desktop styling and a width of 360px. In these cases, to make use of mobile styling and full-width studies on mobile web, you can tell us your window dimensions when Sprig is initialized, and when the window is resized, with the setWindowDimensions
function.
You can further customize study placement and appearance in our dashboard: Settings > Look and Feel. See Study look and feel documentation for more details.
Example of configuring maxHeight
and using setWindowDimensions
:
import Sprig from '@sprig-technologies/sprig-browser';
// or with require() syntax:
// const sprig = require('@sprig-technologies/sprig-browser');
export const Sprig = sprig.configure({
environmentId: '[[ENVIRONMENT_ID]]',
maxHeight: '50%', // sets maxHeight property of the iframe to 50% of page height.
});
// during initialization, and when the window is resized
Sprig.setWindowDimensions([[WIDTH]], [[HEIGHT]]) // [[WIDTH]] and [[HEIGHT]] are pixel numbers
<script>
// at end of installation snippet
Sprig.maxHeight = '50%'; // sets maxHeight property of the iframe to 50% of page height.
// at end of installation snippet, and when the window is resized
Sprig('setWindowDimensions', [[WIDTH]], [[HEIGHT]]) // [[WIDTH]] and [[HEIGHT]] are pixel numbers
</script>
Inject CSS to your studies
For more fine-tuned control of how your study looks, Sprig supports injecting CSS into the survey. Sprig creates a <style/>
tag in the <head/>
of the iframe and sets the CSS string as the text content.
import Sprig from '@sprig-technologies/sprig-browser';
Sprig.styleNonce = 'YOUR_NONCE'; //Optional if your CSP requires nonces
Sprig.applyStyles('.ul-question {color: red}'); //Example: changes question text color to red
<script>
Sprig.styleNonce = 'YOUR_NONCE'; //Optional if your CSP requires nonces
Sprig('applyStyles','.ul-question {color: red}');//Example: changes question text color to red
</script>
Element | CSS Selector |
---|---|
Container | .ul-card__container |
Main question title | .ul-question |
Question subtitle | .ul-caption |
Progress bar | .ul-progress-bar-container |
You may call this method at any time (even when a study is already presented) to override the existing CSS rules. Note that calls to this are not additive, you must include all the CSS changes in one call.
Study Event Lifecycle Notifications
In Sprig SDK version 1.9.0 and above, Sprig introduces several new SDK events and exposes a new way to listen to the updates throughout the study lifecycle. Here is a sample code block for listening to SDK events in real time:
// import the client returned from your Sprig.configure call
import { Sprig } from 'utils/sprig'
// an example of a simple listener
const listener = function (e) {
// does work with data
console.log(e);
};
// to subscribe to Sprig study presented event
Sprig.addListener(Sprig.UPDATES.SURVEY_PRESENTED, listener);
// to remove a study presented event listener
Sprig.removeListener(Sprig.UPDATES.SURVEY_PRESENTED, listener);
<script>
// an example of a simple listener
const listener = function (e) {
// does work with data
console.log(e);
};
// to subscribe to Sprig study presented event
Sprig('addListener', Sprig.UPDATES.SURVEY_PRESENTED, listener);
// to remove a study presented event listener
Sprig('removeListener', Sprig.UPDATES.SURVEY_PRESENTED, listener);
</script>
The following supported events are available on Sprig.UPDATES
:
UPDATES Name | Data | SDK Version | Description |
---|---|---|---|
SDK_READY | { name: 'sdk.ready' } | 2.10.0 | Trigger: when sdk is loaded and initialized |
VISITOR_ID_UPDATED | { name: 'visitor.id.updated' } | 2.10.0 | Trigger: when visitor id is updated |
SURVEY_DIMENSIONS | { name: 'survey.dimensions', contentFrameHeight: int, contentFrameWidth: int } | 2.9.0 | Trigger: on dimension changes. Data: height and width in the event data. |
SURVEY_HEIGHT | { name: 'survey.height', contentFrameHeight: int } | 1.9.0 | Trigger: on height changes. Data: height in the event data. |
SURVEY_WILL_PRESENT | { name: 'survey.will.present', 'survey.id': surveyId } | 2.15.15 | Trigger: immediately before study will be presented. data parameter includes the survey id |
SURVEY_PRESENTED | { name: 'survey.presented' } | 1.9.0 | Trigger: on study present |
SURVEY_APPEARED | { name: 'survey.appeared' } | 2.10.0 | Trigger: when study has appeared on screen |
SURVEY_WILL_CLOSE | { name: 'survey.willClose', initiator: 'survey.completed' } | 2.5.0 | Trigger: immediately before study frame dismiss (notable initiator values: 'close.click' on close button click; 'survey.completed' on survey completion) |
SURVEY_CLOSED | { name: 'survey.closed' } | 1.9.0 | Trigger: on study frame dismiss (including submission and close) |
SURVEY_LIFE_CYCLE | { state: 'presented' } or { state: 'dismissed' } | deprecated | Trigger: on survey present and close. Data: lifecycle state type |
Performance
In the modern web, performance is a critical part of any successful website. At Sprig, we ensure that you can get deep insights about your users without sacrificing your site's performance.
Speed impact on your website
The script is loaded asynchronously, so it does not impact website load times or scroll performance.
File Sizes:
The Sprig JS SDK is broken up into 2 JS files: a controller and a view.
controller.js: 214 kB
The controller is responsible for keeping track of your users and your interface to track events and set attributes and identities. A vast majority of sessions are not shown studies, so we separated the view into a separate file, reducing data usage for your users.
view.js: 285 kB (users only download this when a study is presented to them)
The view contains the code to show the study and send the responses to Sprig.
Availability and Load time:
The Sprig client-side script is hosted on a leading global CDN powered by AWS CloudFront. This allows for the fastest load times by hosting the script as close to the users as possible.
Supported Browser Versions:
The Sprig client-side script is tested against all modern browsers, including:
- Chrome, Firefox, and Safari - latest versions
- Microsoft Edge 40+
Info
As Chrome and Firefox are on 6-week release cycles, best-effort support is given to older releases.
CPU Usage:
Sprig adds minimal CPU overhead (less than 0.1%), leaving application responsiveness virtually untouched. Our cross-browser testing suite ensures that Sprig remains performant across all browsers.
Updated about 2 months ago