Client Scripts

Sometimes you need client-side code that does not map to a component.

There are two main ways to achieve this in îles.

Client Script Block

îles provides support for a script client block in Vue single-file components.

<script client:load lang="ts">
console.log('Powered by îles 🏝', '')

Client script blocks are completely detached from the Vue component, which will be statically pre-rendered. The strategy is applied to the script, not the component.

The script will be injected every time the component is rendered, and it's guaranteed to execute after all elements rendered by the component are in the DOM.

<script client:load lang="ts">
document.getElementById('sidebar').classList.toggle('live') // always works

  <div id="sidebar"/>

If you need code to execute once, use script client in a layout.

Execution Strategies

Other strategies that we saw in the previous section are supported, but you must export onLoad.

This function will be called when the condition for the selected strategy is met—when the element becomes visible if using client:visible, when the media query matches if using client:media, etc.

<script client:visible lang="ts">
console.log('Not necessarily visible')

export function onLoad () {
  console.log('Now visible')

Vanilla Components 🍦

.js and .ts files can also be used as client scripts in îles, and you can choose where to place them by rendering them as islands.

<script setup lang="ts">
import GalleryPreloader from '~/logic/imagePreloader' // .ts

  <GalleryPreloader client:visible/>

You must provide a client: strategy when using vanilla components.

Vanilla components should export a function to call when the selected hydration strategy is fulfilled.

export const onLoad = () => fetch('/images').then(...)

If you need to use the provided parameters, use the OnLoadFn typings:

import type { OnLoadFn } from 'iles'

export const onLoad: OnLoadFn = (el, props, slots) => {
  // Do whatever you need with the element.
Why not use a renderless component?

The benefit is that vanilla JS doesn't require a runtime, so the final bundle size will be smaller.

If your app already uses a framework in some of the islands, then use whatever you find more natural.

Last Updated: