Subscribe on changes!

Add ability to teleport the content into the target after and before specified element

avatar
Mar 13th 2022

What problem does this feature solve?

It allow you to teleport the content to position between two elements instead of always on the end of container.

For example, you can teleport tags into <head>, but It will always be at the end of block. But if you are teleporting something like title, you would want to it to be on the start.

And another use case is insert the tags into <body> but before the <div id="app"> . Which is also another thing you can't do currently.

And most importantly, this fix the problem that you can't hydrate the content correctly when target container already have contents.

Hydration always looks up node from beginning of container. While CSR implementation insert it to the end of the container. They don't share the same order. Currently, Inject pre-rendered content in position CSR will do will never hydrates.You need to insert it into start instead. But that is the wrong order.

(Ignore the space and new line, they are for readability reason)

<Teleport to="#t">
  <span />
</Teleport>
<div id="t">
  <div>Already exist</div>
</div>

In csr, this results in

<div id="t">
  <div>Already exist</div>
  <span />
</div>

But in SSR you need to output it like this to make it be able to be hydrated.

<div id="t">
  <span />
  <div>Already exist</div>
</div>

What does the proposed API look like?

<Teleport to"="body" after="#app" before="#anchor">
  <div id="modal"></div>
</Teleport>
<body>
  <div id="app"></div>
  <template id="anchor"></template>
  <another-element></another-element>
</body>

And dom results in

<body>
  <div id="app"></div>
  <div id="modal"></div>
  <template id="anchor"></template>
  <another-element></another-element>
</body>

When before is specified, the teleport send content before the specified element.

When after is specified, the SSR hydration process treat node after the after target as first node of the teleported content. Which is optional if you don't care about SSR.

By specifying both, you can teleport elements to exact position of the DOM while keep them behaves the same in CSR and SSR

Note: It isn't really a big change from current implementation. I played with it a bit and it surprisingly requires only 20 lines of code change (for a incomplete implementation, multi zone in same target is not handled correctly). test commit