This website works best with JavaScript enabled. Learn how to enable JavaScript.

How to Use VWO for Single Page Applications

Last updated

SPAs are applications that run in a browser and do not require a page load during use.  The following high-level steps provide an overview of how SPAs work:

  1. The browser downloads the entire application as a web document.
  2. The browser executes JavaScript to identify different sections of the application (based on the hash marks or URLs used to identify a section).
  3. When a user navigates through the application, the browser renders the content from the specific sections, without reloading the entire page from the server.

To use VWO for your single page applications, all you need is to do is add the following VWO SPA code snippet in the head section of your website site:

 <script type='text/javascript'>
var _vwo_code=(function(){
var account_id=1, //YOUR_ACCOUNT_ID
settings_tolerance=2000,
library_tolerance=2500,
use_existing_jquery=false,
is_spa = 1,
/* DO NOT EDIT BELOW THIS LINE */
f=false,d=document;return{use_existing_jquery:function(){return use_existing_jquery;},library_tolerance:function(){return library_tolerance;},finish:function(){if(!f){f=true;var a=d.getElementById('_vis_opt_path_hides');if(a)a.parentNode.removeChild(a);}},finished:function(){return f;},load:function(a){var b=d.createElement('script');b.src=a;b.type='text/javascript';b.innerText;b.onerror=function(){_vwo_code.finish();};d.getElementsByTagName('head')[0].appendChild(b);},init:function(){settings_timer=setTimeout('_vwo_code.finish()',settings_tolerance);var a=d.createElement('style'),b='body{opacity:0 !important;filter:alpha(opacity=0) !important;background:none !important;}',h=d.getElementsByTagName('head')[0];a.setAttribute('id','_vis_opt_path_hides');a.setAttribute('type','text/css');if(a.styleSheet)a.styleSheet.cssText=b;else a.appendChild(d.createTextNode(b));h.appendChild(a);this.load('//dev.visualwebsiteoptimizer.com/j.php?a='+account_id+'&u='+encodeURIComponent(d.URL)+'&f='+(+is_spa)+'&r='+Math.random());return settings_timer;}};}());_vwo_settings_timer=_vwo_code.init();
</script>
<!– End Visual Website Optimizer Asynchronous Code –>

ATTENTION Make sure to replace the account_id value in the code with your actual VWO account ID.

Types of SPAs

All interactions with an SPA take place on one page. Some examples of SPAs are Gmail and Google Maps. There are two types of SPAs:

  • SPAs that change URLs
  • SPAs that do not change URLs

SPAs that change URLs

By default VWO supports integration with SPAs that change URLs. You need not add any additional code to track SPAs that uses Hashmark or HTML5 History API.

SPAs that use Hashmark (#)

Refers to applications that use hashmarks (#) in their URL to route users to different sections of the application. The hashmark (#) is an identifier used to point the browser to a specific page or section of the application. These hashmarks (#) are not sent to the server as an HTTP request, and are only used as crawlers to let your server know which section of the application to display.

Example: Consider a URL http://example.com/sports.html#football. The hashmark (#) here identifies the section of the application that refers to football. The part of the URL after # changes for every section in the application.

SPAs that use HTML5 History API

Refers to single page applications that do not use hash marks (#), but change the URL every time a user visits a section in the application using HTML5 History API. Such SPAs allow you to change the URL displayed in the browser through JavaScript, without having to reload the page.

Example: Consider a URL http://example.com/sports.html/football. The “/football” part of the URL identifies the content section that the user is currently accessing. Navigating to another sports section will simply change the “/football” to “/hockey” without reloading the entire page from the server (using history API).

SPAs that do not change URL

Refers to applications that does not hash marks (#) or change URL when visitors land on a section in the application.

To run VWO on such SPAs, you must create a virtual URL for the pages or sections using a custom URL. To enable this, you must add JavaScript code that will execute every time the page/section changes or for any tests you want to run on the applications.

  1. Add the VWO code snippet in the head section of the site.
  2. Execute the following code on the location change success event or at any time you want to run the campaign.

window.VWO = window.VWO || [];
window.VWO.push(['activate', {
customUrl: 'NEW_VIRTUAL_PAGE_URL' // Set your custom URL here
}]);

Using Custom URLs for SPA

Most SPAs load website resources on the first page load. Thereafter, the URLs of the website does not change. For example, a flight booking website wherein the URL remains the same even if you navigate to different sections of the page.

Using Custom URLs you can set up imaginary URLs to find and remember specific sections or pages of the website. Custom URLs allow you to track multiple pages of your website even if the website pages do not have a consistent pattern. There are two different use cases for using custom URL on SPAs:

  1. If actual url does not change and you want to run the test on custom URL, use following code snippet. 
    window.VWO = window.VWO || [];
    window.VWO.push(['activate', {
    customUrl: 'http://mycustomurl.com/custom-url'
    }]);
  2. If actual URL is changing and you want to change the custom URL, use the following code snippet to update the custom URL:
    (function () {
    window._vwo_evq = window._vwo_evq || [];
    var _vwoOldPush = window._vwo_evq.push;
    window._vwo_evq.push = function() {
    var eventData = arguments[0];
    if(eventData[0] === 'uC') {
    // Add your custom url here
    window._vis_opt_url = 'NEW_CUSTOM_URL';
    }
    _vwoOldPush.apply(window._vwo_evq, [].slice.call(arguments));
    };
    })();

Changing Timeout Duration

By default, VWO applies change on any element that loads within 2 seconds on the page after any URL update. If you want to modify the timeout, use the following API.

window.VWO = window.VWO || [];
window.VWO.push(['updateSPAWaitTime', <time_in_ms>]);

Where, time_in_ms is the time in milliseconds.

Apply changes manually

You can manually apply changes to using the following API call. This will be useful for dynamic content, such as infinite scrolling cases, modal boxes, and other similar cases of dynamic content. 

window.VWO = window.VWO || [];
window.VWO.push(['applyChanges', <Array_of_exp_ids>]);

Where, Array_of_exp_ids is an array containing all test Ids to apply changes.

Revert CSS changes manually

To revert the CSS of any test using API, use the following call function. 

window.VWO = window.VWO || [];
window.VWO.push(['revertChanges', <exp_id>]);

Note: You can not revert JS changes or editor changes. This API will only revert the CSS changes.

Applying Changes on Dynamic Elements

If your website has dynamic content which are changed by ajax calls or some other ways, you can use refreshElement API call to instruct VWO to update the dynamic content. 

VWO.push(['refreshElements', <Array_of_selector_paths>, <exp_ids>]);

For example,

VWO.push(['refreshElements', ['#phone-name']]);

Use the following code to apply changes on dynamic elements of the website: 

/* CUSTOM CODE */
vwoRequestAnimationFrame = window.requestAnimationFrame || function (fun) {
setTimeout(function (){
fun();
}, 17)
}
vwoRequestAnimationFrame(function apply() {
// Change the below line with the action to be performed inside setInterval
VWO.push(['refreshElements', ['.hs-button']]);
vwoRequestAnimationFrame(apply);
});

If the changes are still not being applied, then you can force the change by manually calling activate function in setinterval (Use this with precaution as it may cause the website to lag). 

VWO.push(['activate', <should_keep_interval_running>]);

Known Issues/Limitations

The SPA integration module is continuously evolving and we are working hard to improve the feature. We have compiled a list of known issues that VWO users may encounter during the integration. Please reach to us at support@vwo.com for any assistance or information about SPA integration.

  • SPA Integrations for third-party tools are in development and will be announced when available. You can reach our support team for any related queries.
  • Most SPA frameworks like Angularjs and Reactjs use bindings to update DOM content.  If you have applied a conflicting change on the page using VWO editor, updates may not reflect on the page.
  • If you are running a Split URL test on SPA websites that has HTML5 with History mode enabled, you may see the control briefly till the page is refreshed and loaded again.
  • Changes applied to JS/CSS will not be removed/reverted until page refresh. If you want to revert changes manually, refer to the ‘Revert CSS changes manually’ section above.
  • You many notice that sometimes the original content of the page displays despite using the hide element option. This happens because most SPA framework render their content component-wise. Your changes will reflect after a page refresh.

Was this article helpful?

Thanks for your feedback!
Please email us at support@vwo.com to tell us what you were looking for. We'll send the answer to your inbox.

Contact Us / Login