-
Hi, I'm looking for an elegant way to do stuff to an element after it's been added to dom. Currently I wait with timer and document.getElementByID('webglCanvasElement') but want something more direct. Is there a way to do something like this with vanJS or regular JS? Basically I want a signal once the element has been added to dom so I can get reference to it. const MountExample = () => {
prnt('mount example')
const canvasEl = canvas({
id: 'webglCanvasElement',
width: 200,
height: 200,
style: 'background:orange;position:absolute;border:3px solid red;',
onmount: (el) => {
prnt('mounted!', el)
// Initialize WebGL context
const gl = el.getContext('webgl')
if (!gl) {
console.error('WebGL not supported')
return
}
// Do webgl stuff
const vertexShader = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vertexShader, `
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
`)
gl.compileShader(vertexShader)
}
})
return div(canvasEl)
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
For now this workaround does the job: const withMount = (element, onMount) => {
// Try immediate check first
if (element.isConnected) {
onMount(element)
return element
}
// Fall back to observer if not immediately connected
const observer = new MutationObserver(mutations => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node === element) {
onMount(element)
observer.disconnect()
return
}
}
}
})
observer.observe(document.body, {
childList: true,
subtree: true
})
// Also check next frame in case we missed it
requestAnimationFrame(() => {
if (element.isConnected) {
onMount(element)
observer.disconnect()
}
})
return element
}
const MountExample = () => {
const canvasEl = canvas({
width: 200,
height: 200,
style: 'background:orange;position:absolute;border:3px solid red;'
})
return div(
withMount(canvasEl, (el) => {
prnt('mounted!!', el)
// Do WebGL initialization etc
})
)
} |
Beta Was this translation helpful? Give feedback.
-
See #376 for a detailed discussion of the topic (the thread talks about |
Beta Was this translation helpful? Give feedback.
See #376 for a detailed discussion of the topic (the thread talks about
unmount
butmount
should be the same).