Please note this is in the latest version of our Conversion Package so you may be using an older version. If you are unsure please contact the support team.
What is a Single Page Application?
A Single Page Application (SPA) is a web app that loads a single HTML page and dynamically updates the content without refreshing the page.
Why is this relevant to WTO?
By default, Optimize will only evaluate and execute your experiences once as the page loads. Since SPAs do not trigger traditional page loads, additional logic is needed to ensure tests are evaluated and served when necessary within SPAs
Configuration
An example of the config you should expect is:
WT.SPA = {
regex: /portion-of-site-that-is-an-SPA/i,
method: function() {
return thingToLookFor; // method goes here
}
};
Available options
The options available for the SPA configuration are:
Name | Data type | Explanation |
regex
| Regular Expression, or Array of Regular Expressions | A check against the full URL. Can be used to avoid the functionality running unnecessarily. |
method | Function Must return a value | Information to be looked up and compared to previous states to confirm that a route change has taken place and re-execution is necessary. |
Examples of Methods:
Method | Explanation |
| Monitor the entire URL for any change |
| Monitor for changes in the path, example checkout/billing to checkout/payment |
| Monitor for hash changes, example #billing to #payment |
| Monitor for changes in a URL parameter value for a specified key, for example step=billing to step=payment |
WT.SPA = {
regex: /\/checkout\//i,
method: function() { return document.location.pathname }
};In the above example, the SPA configuration would only be triggered on pages where the URL contains /checkout/. We then compare the URL Path for changes from the previous check, and if found, will re-execute your experiences.
What if my URLs are not reliable or don't update?
method is a function that lets you check against any condition and return a value. It does not need to be a URL/pathname check.
For example, if you need to find the name of an "active step" in your navigation, you can have a method function like:
method: function(){
return document.querySelector('nav li.active span').textContent
}So, as long as there is something on the page that we can check against, the above approach will be suitable for you.
Removing changes when the page changes (SPA module v2)
In a Single Page Application, the page does not reload when a visitor moves to a new route. With the original SPA module, changes made by an experience could stay on screen after the visitor moved to a page where the experience should not run.
SPA module v2 fixes this. On every route change it:
Hides the page, using your normal masking settings.
Removes all changes made by Visual Editor experiences.
Re-evaluates your experiences against the new URL.
Applies only the experiences that match, then shows the page.
How to get SPA module v2
Choose one option:
Ask your Account Manager or the Service Desk to update the tag for you.
Update the tag yourself with the three scripts below.
Updating the tag yourself
Requirement: your tag must use library version 7.0. On older library versions the module still detects route changes, but it does not remove changes.
Open your tag configuration and create a draft.
Add Script 1 and then Script 2 to the Global Tag Script, in that order. If you use the original SPA module, replace its scripts.
Add Script 3 to the Tag Trigger Script. If you use the original SPA module, replace its script.
Test the draft tag on your site, then publish it. See QA Guide - Updating your tag.
Optional setting. By default, a route change is a change to the URL path. If your site also changes pages through the query string or the hash, add one of these lines above Script 1:
WT.spaConfig = { compare: 'path+search' }; // path and query string
WT.spaConfig = { compare: 'href' }; // full URL, including the hash
Script 1 - Global Tag Script (module)
/**
* WEBTRENDS OPTIMIZE - SINGLE PAGE APP MODULE v2 : PREINIT MODULE
* @requires WT.optimizeModule.prototype.wtConfigObj.libUrl = 'https://c.webtrends-optimize.com/acs/common/js/7.0/wt_lib.js';
* @trigger route-change.js calls WT.refreshAndExecute() on every route change
*
* v2: before re-deciding, every change the previous page's tests made is torn down through the
* lib's applied-changes registry (WT.optimize.teardown), so a test cannot leak onto a page whose
* location it doesn't match. Requires lib 7.0 with WT.optimize.applied; on older libs the module
* behaves exactly as v1.
*/
// Tell lib 7.0 to capture undo information for every change it applies (read at lib load).
WT.optimizeModule.prototype.wtConfigObj.spaTeardown = true;
WT.spa = WT.spa || {};
WT.spa.version = '2.0.0';
// Undo everything the current page's tests applied. Safe to call on any lib version.
WT.spa.teardown = function (filter) {
try {
if (WT.optimize && typeof WT.optimize.teardown === 'function') {
return WT.optimize.teardown(filter);
}
} catch (err) {
if (document.cookie.match(/_wt.bdebug=true/i)) console.log('WTO SPA teardown failed', err);
}
return null;
};
WT.refreshAndExecute = function(){
// Capture the display mode/overlay BEFORE WT.optimize._ctor() runs below: _ctor wipes
// g_ConfigParams and (in lib 7.0) does NOT re-seed s_pageDisplayMode/overlayColor, which the
// lib's show-back (z2d27) reads to un-hide the page. Without restoring them a navigation whose
// destination renders no matching test can leave the page stuck at display:none.
var PDM = WT.optimizeModule.prototype.wtConfigObj.s_pageDisplayMode;
var OVERLAY = WT.optimizeModule.prototype.wtConfigObj.overlayColor;
// Page hide -- INITIALISE.
WT.hideAndShow(document.body, PDM, false, OVERLAY);
if(["shift", "overlay"].includes(PDM)){
WT.hideAndShow("body", PDM, false, null);
}
// Teardown -- undo the previous page's tests while the page is hidden, before the lib state is reset.
WT.spa.teardown();
if(WT.optimizeModule.prototype.checkWhitelist_CUSTOM) {
WT.optimizeModule.prototype.checkWhitelist_CUSTOM();
WT.fireEvent(new WT.Event("hide_show",WT.Event.STATUS_SUCCESS,document.body,{
displayType: 'custom',
display: false
}));
}
// cache pv and hideshow listeners
var temp = {};
["hide_show", "pageview"].forEach(function(e){
if( WT.optimize.g_ConfigParams.s_eventHandlers[e] && WT.optimize.g_ConfigParams.s_eventHandlers[e].success && WT.optimize.g_ConfigParams.s_eventHandlers[e].success.length ){
if(!temp[e]) temp[e] = [];
WT.optimize.g_ConfigParams.s_eventHandlers[e].success.forEach(function(f){
temp[e].push(f);
});
}
});
WT.optimize._ctor();
// Restore what _ctor wiped.
WT.optimize.g_ConfigParams.s_otsServer = "pat.webtrends-optimize.com";
WT.optimizeModule.prototype.wtConfigObj.s_otsServer = "pat.webtrends-optimize.com";
WT.optimize.g_ConfigParams.s_pageDisplayMode = PDM;
WT.optimize.g_ConfigParams.overlayColor = OVERLAY;
// Defensive: if the lib evaluated before the spaTeardown flag was set (load order), the lib's
// auto-enable saw it unset. Enable the registry here so teardown works on every route change.
if (WT.optimize.applied && !WT.optimize.applied.enabled) WT.optimize.applied.enable();
// rebuild hooks
for(var ev in temp){
var list = temp[ev];
list.forEach(function(f){
WT.addEventHandler(ev, f);
});
}
// Trigger SPA Hooks
WT.fireEvent(new WTEvent("spa_start", WTEvent.STATUS_SUCCESS,document,{}));
// Safety net: never leave the page hidden.
var wtoRevealPage = function(){
WT.hideAndShow(document.body, PDM, true, OVERLAY);
// Defensive: the lib's removeStyleSheet clears only the first #wt_StyleSheet (getElementById),
// so sweep any duplicate page-hide stylesheets that any path may have left behind.
var n; while ((n = document.getElementById('wt_StyleSheet')) && n.parentNode) { n.parentNode.removeChild(n); }
};
WT.addEventHandler('done', wtoRevealPage, wtoRevealPage);
WT.execute(WT.optimizeModule.prototype.wtConfigObj);
// Last resort, only if the cycle never fires 'done' at all (hung/errored decide): reveal after
// the lib's own page timeout has had its chance.
if (WT.spa._revealTimer) { clearTimeout(WT.spa._revealTimer); }
WT.spa._revealTimer = setTimeout(wtoRevealPage, (parseInt(WT.optimizeModule.prototype.wtConfigObj.s_pageTimeout, 10) || 3000) + 250);
};
Script 2 - Global Tag Script (route change detection)
//ROUTE CHANGE : SPA v2
(function routeChange() {
try {
var log = WT.helpers.bdebug.log;
if (WT.routeChangeEvent) return;
var config = WT.spaConfig || {};
var compare = config.compare || 'pathname';
var key = function () {
switch (compare) {
case 'href': return window.location.href;
case 'path+search': return window.location.pathname + window.location.search;
default: return window.location.pathname;
}
};
var currentKey = key();
var scheduled = false;
var check = function () {
if (scheduled) return;
scheduled = true;
// Coalesce pushState + popstate + mutations from the same navigation into one refresh.
setTimeout(function () {
scheduled = false;
var next = key();
if (next === currentKey) return;
currentKey = next;
log('WTO SPA: route change -> ' + next);
window.dispatchEvent(new CustomEvent('WTO:route-change', {
detail: { pageUrl: window.location.pathname, key: next }
}));
WT.refreshAndExecute();
}, 0);
};
// History API.
['pushState', 'replaceState'].forEach(function (method) {
var original = window.history[method];
if (typeof original !== 'function') return;
window.history[method] = function () {
var result = original.apply(this, arguments);
try { check(); } catch (err) { if (document.cookie.match(/_wt.bdebug=true/i)) console.log('WTO SPA ' + method + ' hook', err); }
return result;
};
});
window.addEventListener('popstate', check);
window.addEventListener('hashchange', check);
// Fallback for routers that change the URL without the History API
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
if (MutationObserver) {
var observer = new MutationObserver(check);
observer.observe(document, { subtree: true, childList: true });
} else {
log('browser doesn\'t support mutationobserver');
}
WT.routeChangeEvent = true;
} catch (err) {
if (document.cookie.match(/_wt.bdebug=true/i)) console.log(err);
}
}());
Script 3 - Tag Trigger Script
/**
* WEBTRENDS OPTIMIZE - SINGLE PAGE APP MODULE v2 : POST LOAD SETUP REPLACEMENT
*/
WT.optimize.setup=function(arg1,arg2){
WT.Debug.info("OVERWRITTEN SETUP CALL");
try{
if(WT.optimize.g_Aborted){
WT.Debug.error("setup: Aborted due to prior error, check error message for details.", 0);
return
}
var params={};
if(typeof arg1=="object") params=arg1;
else if(typeof arg1=="string"){
if(typeof arg2!="undefined") params=arg2;
params["testAlias"]=arg1
}
if(typeof arg1!="string"){
if(WT.optimize.g_hasEmptySetup){
WT.Debug.error("setup: Only one empty setup call is supported.",0);
return
}
// CHANGE HERE
// WT.optimize.g_hasEmptySetup=true;
}
if(typeof arg1=="string")
for(var i in WT.optimize.g_ParamsList)
if(arg1==WT.optimize.g_ParamsList[i]["testAlias"]){
WT.Debug.error("setup: Duplicate setup calls with the same alias are not supported.", 0);
return
}
params["s_requestType"]="control";
if(!WT.optimize.g_ConfigLoaded){
var obj=this;
WT._addEventHandler(WTEvent.CAPI_CONFIG_PROCESSED,function(){
obj._initialize(params)
});
WT.hideAndShow(document.body,this.g_ConfigParams["s_pageDisplayMode"],false,this.g_ConfigParams["overlayColor"])
} else this._initialize(params)
}catch(e){
WT.Debug.error("setup: Fatal error, check error message for details.",0,e);
var event=new WTEvent(e.wtevent?e.wtevent:WTEvent.ABORT,WTEvent.STATUS_FAULT,this);
event.params["error"]=e;
WT._fireEvent(event)
}
};
WT.optimize.setup = WT.optimize.setup.bind(WT.optimize);
WT.refresh = function(){
try{
// v2: undo the previous page's tests before the lib state is reset (WT.execute calls this first).
if (WT.spa && WT.spa.teardown) WT.spa.teardown();
WT.optimize.g_hasEmptySetup=false;
WT.optimize.g_Aborted=false;
WT.optimize.g_RunObjList=[];
WT.optimize.g_ParamsList=[];
WT.optimize.g_PageTimer=null;
WT.optimize.g_PageStartTime=null;
WT.optimize.g_PageEndTime=null;
WT.optimize.Preview={};
// WT.optimize._ctor();
var tmp=WT.optimize.Library.DynamicID;
var fn = WT.optimize._Library || WT.optimize.zd67f;
WT.optimize.Library=new fn(WT.optimize);
WT.optimize.Library.DynamicID=tmp;
}catch(e){
WT.Debug.error("refresh: Fatal Error, check error message for details",0,e);
var event=new WTEvent(e.wtevent?e.wtevent:WTEvent.ABORT,WTEvent.STATUS_FAULT,this);
event.params["error"]=e;WT._fireEvent(event)
}
};
WT.optimize.setup(WT.optimizeModule.prototype.wtConfigObj);
After you upgrade
Re-save existing Visual Editor experiences. Open each one and quick save it. Experiences that are not re-saved continue to run, but their changes are not removed on route change.
New Visual Editor experiences need no extra steps.
Advanced Editor code is not removed automatically. Use
WT.onTeardown()to undo your own changes. See Available methods in the Web Client API.
Tags that do not use the SPA module are not affected.
