Initializing components
Create sliders, maps and widgets when their page appears, and destroy them when it goes away.
Pagefold swaps the HTML but does not know about the JavaScript you attached to it. A slider on the old page keeps its listeners and timers after its element is gone, and the slider on the new page does not exist yet.
Pagefold gives you mount for this. It runs your setup for every element that matches a selector, now and after each visit, and runs the cleanup you return when the element leaves the page.
pagefold.mount('[data-slider]', (el) => {
const slider = new Slider(el)
return () => slider.destroy()
})
setupreceives the element. Return a function to tear it down. It is optional, but without it nothing is released when the page goes away.- Each element is set up once and cleaned up once, however many visits come and go.
mountreturns a function. Call it to stop watching the selector and clean up everything it started.pagefold.destroy()cleans up every component.- A component that throws is reported in the console and left alone. The others, and the visit, are not affected.
- Elements kept with
data-pagefold-persistare the same element before and after, so they are not set up twice.
What happens, step by step
A visit from a page with one slider to a page with two:
| Moment | mount does |
|---|---|
You call mount | The first slider is set up |
content:replace fires | The old slider’s element is gone, so its cleanup runs. The two new elements are found and set up |
| The visit ends | A last check, for containers that stayed until the end, such as the previous page with Overlap |
| Back button, to the first page | The two are cleaned up and one is created |
The cleanup runs after the old element has left the page. If it needs the element to still be there, use the hook content:replace with before and clean up in it yourself.
Common problems
- Two sliders on the same element. You attached them somewhere other than
mount, such as aDOMContentLoadedlistener that also runs on the first page. Keep one place that creates components. - Memory grows with every visit.
setupreturned nothing, so the old instance was never destroyed. Always return the cleanup, even when it only removes a listener. - The component flickers when the page appears. It is created after the transition has already started showing the page.
mountalready sets components up oncontent:replace. If you create them yourself invisit:end, move them tomount. - Scripts in the page do not run. Inline
<script>tags are not part of this. See Scripts for new scripts in the incoming page.