aboutsummaryrefslogtreecommitdiff
path: root/src/lib/BackgroundImage.svelte
blob: 0b2f04324e377e8b2aba61b20c70e3984d3ef963 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<script lang="ts">
	import { onDestroy, onMount } from 'svelte'
	import { browser } from '$app/env'

	export let url: string
	let styleHtml = `<style class="background-image-style">:root{--background:url(${url})}</style>`
	let serverSideRenderedStyleShown = true

	function updateUrl() {
		if (!browser) return

		for (const styleEl of document.getElementsByClassName('background-image-style'))
			styleEl.innerHTML = ''

		// add bodyStyle to the head
		const style = document.createElement('style')
		style.classList.add('background-image-style')
		style.innerHTML = `:root{--background:url(${url})}`
		document.head.appendChild(style)
	}

	$: [url, updateUrl()]

	onMount(() => {
		serverSideRenderedStyleShown = false
	})

	// get rid of the body style when we leave the page
	// not doing this will sometimes cause the background to stay
	onDestroy(() => {
		if (browser) {
			for (const styleEl of document.getElementsByClassName('background-image-style'))
				styleEl.innerHTML = ''
		}
	})
</script>

<svelte:head>
	{#if serverSideRenderedStyleShown}
		{@html styleHtml}
	{/if}
</svelte:head>