Skip to content

Converts your JavaScript code, stored in files, into a custom blade directive and inline it in HTML. Also allows transform JS code along the way.

License

Notifications You must be signed in to change notification settings

Zmyslny/laravel-inline-scripts

Repository files navigation

Laravel Inline Scripts

Build Status Latest Version

A Laravel package that provides a simple way to wrap your JavaScript code stored in a file and inline it as custom Blade directive.

Allows ✨:

  • passing variables from PHP to JavaScript,
  • process / modify the script in a dedicated PHP class.

Additionally - has build in ready-to-use scripts (built using this package):

  • two states - light / dark - color scheme switching script (+ view with icons)
  • three states - light / dark / system - color scheme switching script (+ view with icons)
  • more to come

Requirements

  • PHP 8.2 or newer
  • Laravel 9.x or newer (did not test with older versions)

🚀 Quick Start

Install the package via Composer:

composer require zmyslny/laravel-inline-scripts

Register a custom Blade directive for your JavaScript in your AppServiceProvider:

class AppServiceProvider extends ServiceProvider 
{
    public function boot(): void 
    {
        BladeInlineScripts::takeFiles(
            resource_path('js/your-first-script.js'),
            resource_path('js/your-second-script.js'),
            ...
        )->registerAs('myInlineScripts');
    }
}

Use the custom Blade directive in your template to inline the scripts:

<html>
<head>
    ...
    
    @myInlineScripts
</head>
<body>
    ...

Done.

What are inline scripts?

Inline scripts are JavaScript code blocks embedded directly into HTML documents. Traditionally, developers manually write these scripts as strings in the <head> section or at the end of the <body> section:

...
<script>
    // Traditional inline script
    document.addEventListener('DOMContentLoaded', function() {
        console.log('Page loaded');
    });
</script>
</head>

This package makes it much more convenient by allowing you to keep inline scripts in separate JavaScript files, which enables ✨:

  • Complex script processing : using dedicated PHP classes (see example bellow)
  • Variable passing : from PHP to JavaScript (see example bellow)
  • Unit testing : your JavaScript code using tools like Vitest or Jest (see bonus section)
  • IDE support : with syntax highlighting and error detection in dedicated JS files (see example bellow)

Advanced Usage: Custom Script Processing

Want to do more advanced processing of your JavaScript code before inlining it?

Create a PHP class:

  • that implements the RenderableScript interface - using it you can fetch / prepare / create JS code in any way you want;
  • and register it using BladeInlineScripts::take(...) method.

Use interface ScriptWithPlaceholders for scripts with placeholders to be replaced with variables.

Want to load JS code from a file? Extend the abstract class FromFile or FromFileWithPlaceholders.

abstract class FromFile implements RenderableScript;

abstract class FromFileWithPlaceholders implements ScriptWithPlaceholders;

Explanation Through Example: Color scheme switch script

Modern websites often provide users with the ability to switch between light and dark themes. In such cases, you might want to remember the user's choice using localStorage and apply the selected theme on page load. To avoid FOUC (Flash of Unstyled Content), you can use inline script to set the theme before the page fully loads.

The folowing example demonstrates by using two-state color scheme switch script (light/dark).

Icons used (from HeroIcons):

View

Three-state (light/dark/system) is also available. Just replace 2-states- | ..TwoStates with 3-states- | ..ThreeStates in the commands and code below.

Using prepared PHP classes

Step 1: Add the following to your AppServiceProvider:

use Zmyslny\LaravelInlineScripts\Ready\ColorSchemeSwitchTwoStates\InitScript;
use Zmyslny\LaravelInlineScripts\Ready\ColorSchemeSwitchTwoStates\SwitchScript;

class AppServiceProvider extends ServiceProvider 
{
    public function boot(): void 
    {
        BladeInlineScripts::take(
            new InitScript(), // initializes the color scheme on page load
            new SwitchScript('d') // toggles the color scheme when the 'd' key is pressed
        )->registerAs('colorSchemeScripts');
    }
}

Step 2: Insert a newly created custom Blade directive in your template:

<html>
<head>
    ... 
    @colorSchemeScripts
</head>
<body>
    ...

Now hit the d key to toggle between a light and dark color scheme, and your choice will be remembered on subsequent visits.

Step 3 (optional): Add the view with color scheme icons to your website:

php artisan vendor:publish --tag=color-scheme-2-states-views

Select the one that suits your frontend and insert it in your template:

  • Blade + TailwindCss + Hero icons: ../views/color-scheme-switch-two-states/hero-icons-tailwind.blade.php
  • Livewire/Alpine + TailwindCss + Hero icons: ../views/color-scheme-switch-two-states/hero-icons-tailwind-alpine.blade.php

Using JS code directly

Step 1: Publish the built-in scripts:

php artisan vendor:publish --tag=color-scheme-2-states-js

That will copy the scripts to resources/js/color-scheme-switch-two-states/[init-script.js, switch-script.js].

Step 2: Register the scripts in your AppServiceProvider:

class AppServiceProvider extends ServiceProvider 
{
    public function boot(): void 
    {
        BladeInlineScripts::takeFiles(
            [
                resource_path('js/color-scheme-switch-two-states/init-script.js'),
                ['__DARK__' => 'dark'], // variables to replace in the script
            ],
            [
                resource_path('js/color-scheme-switch-two-states/switch-script.js'),
                ['__DARK__' => 'dark', '__LIGHT__' => 'light', '__TOGGLE_KEY__' => 'd'], // variables to replace in the script
            ]
        )->registerAs('colorSchemeScripts');
    }
}

Step 3: Insert a newly created custom Blade directive in your template:

<html>
<head>
    ... 
    @colorSchemeScripts
</head>
<body>
    ...

Now hit the d key to toggle between a light and dark color scheme, and your choice will be remembered on subsequent visits.

Step 4 (optional): Add the view with color scheme icons to your website:

php artisan vendor:publish --tag=color-scheme-2-states-views

Select the one that suits your frontend and insert it in your template:

  • Blade + TailwindCss + Hero icons: ../views/color-scheme-switch-two-states/hero-icons-tailwind.blade.php
  • Livewire/Alpine + TailwindCss + Hero icons: ../views/color-scheme-switch-two-states/hero-icons-tailwind-alpine.blade.php

Bonus

Unit tests for JS scripts

php artisan vendor:publish --tag=color-scheme-2-states-js-tests
# or
php artisan vendor:publish --tag=color-scheme-3-states-js-tests

You can also publish JS scripts, JS test files and views at once:

php artisan vendor:publish --tag=color-scheme-2-states-all
# or
php artisan vendor:publish --tag=color-scheme-3-states-all

License

This package is licensed under the MIT License.

About

Converts your JavaScript code, stored in files, into a custom blade directive and inline it in HTML. Also allows transform JS code along the way.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published