Skip to content

Inline Script for Theme Toggle in app.blade.php Should Be Moved to JS File #7754

@naduni-s

Description

@naduni-s

How to use GitHub

  • Please use the 👍 reaction to show that you are interested into the same feature.
  • Please don't comment if you have no relevant information to add. It's just extra noise for everyone subscribed to this issue.
  • Subscribe to receive notifications on status change and new comments.

Is your feature request related to a problem? Please describe.
Yes. The current dark mode theme initialization script is written directly inside resources/views/app.blade.php as an inline <script> tag. While it functions correctly, having this logic inline can cause issues with:

  • While the current dark mode theme logic in app.blade.php works, having it as an inline <script> can lead to problems with Content Security Policy (CSP) headers, layout maintainability, and caching.
  • This kind of logic doesn't belong in a Blade layout file — it's better handled in a JavaScript file.
  • Monica would benefit from separating this theme toggle logic into an external JS file, especially as the project grows or stricter security is introduced.

Describe the solution you'd like
Move the inline script to a dedicated JavaScript file, for example, theme.js or utils/theme.js, and load it using @vite in the Blade template. This way:

  • The logic is centralized in a JS file, making it easier to maintain.
  • It improves compatibility with CSP headers.
  • It enhances caching and reduces layout clutter.

Describe alternatives you've considered (optional)

  • Keeping the logic inline but wrapping it in a @once directive (still doesn't solve CSP/caching concerns).
  • Using a noscript fallback, but it doesn't account for dynamic preference detection or toggling.

Additional context
The current inline script:

<script type="text/javascript">
    if (localStorage.theme === 'dark' || 
        (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
        document.documentElement.classList.add('dark')
    } else {
        document.documentElement.classList.remove('dark')
    }
</script>

Can be moved to a file like resources/js/theme.js and then imported in the Blade view like:

@vite(['resources/js/theme.js'])

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions