Note: This article is about a new method generally available as of June 2021, which replaces the older method. If you are already using SPA, you can find information on the previous method here.
Single-page applications (SPA) are becoming more and more popular in web development. Popular SPA frameworks include React, Vue, AngularJS, Ember, and Backbone. If your website is using one of these frameworks, read this article for the recommended implementation method.
With this solution, the implementation for single-page application is identical to non-single-page applications. There is no need to implement an API call for SPA pageload, or mark which campaigns are relevant for these calls. Moreover, the solution is seamless to the framework.
How it Works
The heavy lifting is done by Dynamic Yield:
- Dynamic Yields monitors loading of page elements, even when the page itself does not fully reload. This is done using a Web API called a MutationObserver, which provides hooks into DOM mutations and enables Dynamic Yield to track when a DOM node is inserted, destroyed or modified. With that, Dynamic Yield applies (or reapplies) changes at the right moment. Once the page deactivates, Dynamic Yield no longer attempts to change the elements on that page.
- The Dynamic Yield script has a state machine, and all of the campaigns are stateful smart objects. This way, the script responds to changes in your applications.
- Our elements are added though the Shadow DOM, in a way that doesn’t interfere with your application lifecycle.
Diagram of the Previous Guidelines and the New Guidelines
To learn more about the difference between the old and the new guidelines - see the technical diagram below.
- Older JS libraries might not be supported. Note that these libraries might be in some Dynamic Yield templates (for example, Swiper is used for carousel experiences).
- The campaign experience CSS is not inherited from the site CSS, and therefore must be added explicitly in the variation code.
- Setting the page context is mandatory.
Page Change/Transition Detection
The SPA solution uses multiple methods to detect changes to the page:
- URL changes are detected using the History API and Hashchange events.
- A MutationObserver is attached to the body element to observe any changes to the elements.
- Detection of the DY.recommendationContext object
URL change detection ignores changes to URL query string parameters.
Dynamic Content and Recommendation campaigns are rendered into the Shadow DOM instead of the DOM directly. As a result, these campaigns do not interfere with the DOM change-detection of the front-end framework.
To enable seamless access to HTML elements of these campaigns, the JS code of the campaigns has multiple querying functions overridden, first querying the Shadow DOMs of the campaigns. If no elements are found, it queries the DOM as a fallback.
These functions are: