Mount calculators in single-page apps
Single-page apps add and remove containers after the page loads, so the loader's one-time scan misses them. The loader adds a window.AztecCalcs object that lets you mount and unmount a calculator yourself.
Before you start
- Add the loader script as in Embed calculators with the loader.
window.AztecCalcsexists once the script has run. - Your page's origin must be in your allowed domains.
Minimal example
Create a container, give it the attributes the loader reads, attach it to the page, and then mount it. The loader needs only data-aztec-calc and data-cobrand-key. Add data-locale only to choose a locale other than your cobrand's default (container.dataset.locale = 'fr-CA').
const container = document.createElement('div');
container.dataset.aztecCalc = 'auto-loan-payment';
container.dataset.cobrandKey = '<your public key>';
document.body.append(container);
const { status } = await window.AztecCalcs.mount(container);
console.log(status); // 'ready' once the calculator is on screen
// Later, when your app removes the calculator:
window.AztecCalcs.unmount(container);
In a framework, mount in the effect or lifecycle hook that runs after the element is in the document, and unmount in its cleanup.
Options
window.AztecCalcs has two methods. Both take the container element and use the same attributes as the loader: data-aztec-calc, data-cobrand-key and the optional data-locale.
| Method | Returns |
|---|---|
mount(element) | A promise that always resolves to { status }. It never rejects. |
unmount(element) | { status }. It never throws. |
Errors and limits
mount resolves with one of these statuses:
| Status | Meaning |
|---|---|
ready | The calculator is on screen. |
failed | The calculator didn't load. The console shows an [Aztec-Calcs] warning with the loader's code, and the container has data-aztec-calc-state="Failed". |
already-mounted | The container already has a calculator, or is loading one. |
invalid | The argument isn't an element, an attribute is missing, or the element isn't in the document. The console shows an [AztecCalcs] warning. |
cancelled | You called unmount before the mount finished. |
unmount returns unmounted, not-mounted or invalid. It aborts a mount in progress, removes the calculator and releases its listeners. After unmount, you can mount the same container again. A container that failed stays already-mounted until you unmount it, so call unmount before you retry.
| Limit | Value |
|---|---|
| Load time | 10 seconds for the calculator code and definition together |
| Loader copies | One for each page. A second script tag doesn't replace window.AztecCalcs. |
| Calculator key | 1 to 64 lowercase letters, digits and hyphens |
Don't call mount before the loader script has run. If your code can run first, wait for the script tag's load event.
Related API reference
See Embed endpoints and allowed domains for the calls the calculator makes. The calculation operations are in the generated reference: