Skip to content

Inline CSS or Javascript #1546

Closed
Closed
@Nick-Mazuk

Description

@Nick-Mazuk

Is your feature request related to a problem? Please describe.

Sometimes, it's just better to inline some Javascript or CSS into the initial HTML page. It can speed up performance and improve user experience. For instance…

  • Inlining critical path CSS
  • Inlining all CSS if the total CSS is small (to prevent a second round trip)
  • Toggling dark mode without causing a "light mode flash" while waiting for the JS to load
  • Inlining font declarations to prevent extra round trips

Describe the solution you'd like

In a layout, you can import JS/CSS with an import tag.

import '$lib/styles.css'

Having the same functionality (not necessarily syntax) for app.html would be excellent. For instance…

<link href="$lib/styles.css" rel="stylesheet" inline="true" />
<script src="$lib/scripts.ts" inline="true"></script>

Could be replaced with this in the HTML sent to the client.

<style>body{background: 'dimgray'}</style>
<script>document.body.classList.add('dark')</script>

I'm sure there's a better syntax for this, so I'm fine if it's different.

Describe alternatives you've considered

You could always just write the CSS or JS straight into src/app.html, and while it works, it's not always possible.

For instance, if your site doesn't use much CSS (often ~10kb or less gzipped), it can be beneficial to inline that CSS directly into the HTML. It can shave off a few hundred milliseconds in load time on a good connection, and more on a slower one. But if you're using something like TailwindCSS, you don't have control over the CSS output. Therefore, you can't inline it.

Likewise if you're Javascript is based on any NPM package. Useful if you have multiple Sveltekit sites and are using NPM packages to share repeated code.

How important is this feature to you?

7/10. Would be super helpful, but not necessary.

Additional context

Not all CSS or JS should be inlined. But having some can really help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions