Appearance
Plinthos Ready Promise
This is a useful snippet for eliminating race conditions in projects where accessing the global Plinthos object during page load is required.
Setup
This Promise
takes advantage of a special event that all Plinthos Snippets dispatch on the document
object when they have finished initializing: 'plinthoskitready'
.
js
export const plinthosReady = new Promise(res => {
if (window.Plinthos) res(window.Plinthos);
else {
document.addEventListener('plinthoskitready', () => {
res(window.Plinthos);
})
}
});
ts
// Add Plinthos to the Window interface
declare global {
interface Window {
Plinthos : Object
}
}
export const plinthosReady = new Promise<any>(res => {
if (window.Plinthos) res(window.Plinthos);
else {
document.addEventListener('plinthoskitready', () => {
res(window.Plinthos);
})
}
});
This Promise
is safe to initialize and reference in code that loads before or after the Snippet's code has loaded.
Usage
js
plinthosReady.then(Plinthos => {
// Plinthos object is initialized and fully populated.
});
Although the global Plinthos
object will be fully populated, it is not guaranteed that Stages set to run on page startup will have actually started at the moment that plinthoskitready
event fires.
This is because the displays
variable is considered fully populated once the Stages have been initialized but due to Plinthos' deferred loading system, some Stage Content (including initial Shots) may still be initializing.
If you need to execute code as soon as a Stage starts, consider listening for the 'start'
StageEvent.