PHPackages                             switch/live - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. switch/live

ActiveLibrary

switch/live
===========

Switch Framework Live SPA-like Navigation, AJAX Partial Swapping &amp; History Engine

00JavaScript

Since Aug 14Pushed yesterdayCompare

[ Source](https://github.com/celionatti/switch-live)[ Packagist](https://packagist.org/packages/switch/live)[ RSS](/packages/switch-live/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (2)Used By (0)

Switch Live (`switch/live`)
===========================

[](#switch-live-switchlive)

[![Latest Version](https://camo.githubusercontent.com/34e695c6016bc2a934a96bed696e29b2f2ab562a7134d65a55d00653cd506bea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e302e302d626c75652e737667)](https://github.com/celionatti/switch-live)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)[![PHP](https://camo.githubusercontent.com/d7583679f2fa23bc68186b2e772180e9fbd9afb79c983dff6b928e19d389aae8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e322d3737376262342e737667)](https://php.net)

**Switch Live** is a zero-dependency, ultra-fast SPA navigation, DOM morphing, and reactive component engine for the **Switch Framework**.

It gives you the reactivity, speed, and smooth UX of modern JavaScript frameworks (like React, Vue, Turbo, and Livewire) directly in native PHP templates — with **zero JavaScript compilation, zero npm packages, and zero build steps**.

---

⚡ Key Features
--------------

[](#-key-features)

- 🚀 **Zero Page Reloads**: Seamless SPA-like link navigation and AJAX form submissions.
- 🧠 **Smart DOM Morphing**: Replaces only changed DOM nodes while preserving input focus, cursor positions, form state, and media playback.
- ⚡ **Hover Prefetching (`switch-prefetch`)**: Preloads destination pages on mouse hover for **0ms perceived latency**.
- 📊 **Automatic Top Progress Bar**: YouTube/GitHub-style animated top loading bar.
- ⏱️ **Intelligent Polling (`switch-poll`)**: Periodically updates widgets with automatic tab-visibility pausing to save CPU and battery.
- 👁️ **Viewport Lazy Loading (`switch-lazy`)**: Loads heavy components on-demand as they enter the screen.
- 🔍 **Debounced Live Search (`switch-search`)**: Real-time filtering and live search with customizable debounce timeouts.
- 📜 **Infinite Scroll (`switch-infinite`)**: Automatically fetches and appends paginated feeds.
- ⚠️ **Confirmation Prompts (`switch-confirm`)**: Built-in confirmation dialogs for destructive actions.
- 🍞 **Server-Sent Toasts &amp; Events (`LiveResponse`)**: Trigger floating notifications, custom JS events, and seamless redirects straight from PHP controllers.
- 🎨 **Hardware-Accelerated Transitions (`switch-transition`)**: Smooth CSS animations between navigations.
- 📱 **100% Mobile-Responsive**: Built-in safe-area insets and touch-friendly controls.

---

📦 Installation
--------------

[](#-installation)

Install via Composer into your Switch project:

```
composer require switch/live
```

---

🚀 Quick Setup
-------------

[](#-quick-setup)

Include `@liveScripts` before the closing `` tag in your layout view (`resources/views/layouts/app.switch.php`):

```
>

    My App

    @liveScripts

```

---

📖 Comprehensive Documentation &amp; Usage
-----------------------------------------

[](#-comprehensive-documentation--usage)

### 1. Seamless SPA Navigation (`switch-to`)

[](#1-seamless-spa-navigation-switch-to)

Add `switch-to` to any `` link or `` to navigate without full page reloads:

```

Dashboard
Profile

    @csrf

    Log In

```

---

### 2. Targeted Component Updates (`switch-target`)

[](#2-targeted-component-updates-switch-target)

By default, Switch Live updates the main container (`[switch-live-root]`). You can target specific sections by providing a CSS selector:

```

Edit User

```

---

### 3. Reactive Button Actions &amp; Payloads (`switch-action`)

[](#3-reactive-button-actions--payloads-switch-action)

Trigger controller actions directly from buttons with custom HTTP methods and JSON data:

```

    + Increment

    Add to Cart

```

---

### 4. Hover Prefetching (`switch-prefetch`)

[](#4-hover-prefetching-switch-prefetch)

Preloads pages into memory the instant the user's cursor hovers over a link:

```

    Analytics (Instant 0ms Load)

```

---

### 5. Debounced Live Search &amp; Real-Time Inputs (`switch-search`)

[](#5-debounced-live-search--real-time-inputs-switch-search)

Trigger live database queries as the user types with automatic debouncing:

```

```

---

### 6. Auto-Polling / Live Widgets (`switch-poll`)

[](#6-auto-polling--live-widgets-switch-poll)

Automatically re-fetches a component on a timed interval. Automatically pauses when the browser tab is hidden:

```

    CPU Load: {{ $stats.cpu }}%
    RAM Usage: {{ $stats.ram }}%

```

---

### 7. Viewport Lazy Loading (`switch-lazy`)

[](#7-viewport-lazy-loading-switch-lazy)

Defers loading of non-critical or slow components until the user scrolls down to them:

```

    Loading sales chart...

```

---

### 8. Infinite Scroll &amp; Append (`switch-infinite`)

[](#8-infinite-scroll--append-switch-infinite)

Fetch and append new rows to a feed when the user scrolls to the bottom of the page:

```

        {{ $post.title }}

    Loading more posts...

```

---

### 9. Confirmation Dialogs (`switch-confirm`)

[](#9-confirmation-dialogs-switch-confirm)

Prevent accidental submissions or deletions with confirmation dialogs:

```

    Delete Account

```

---

### 10. Disable &amp; Loading Indicators (`switch-disable` &amp; `switch-indicator`)

[](#10-disable--loading-indicators-switch-disable--switch-indicator)

Prevent duplicate form submissions and show loading spinners while requests are in flight:

```

    @csrf

        Place Order

        Processing payment...

```

---

### 11. CSS Page Transitions (`switch-transition`)

[](#11-css-page-transitions-switch-transition)

Apply smooth animations between page transitions:

```
About Us
```

---

### 12. Scroll Preservation (`switch-preserve-scroll`)

[](#12-scroll-preservation-switch-preserve-scroll)

Maintain the user's scroll position when liking a post, submitting a form, or clicking pagination:

```

    @csrf
    ❤️ Like

```

---

🖥️ Server-Side Control (`LiveResponse`)
---------------------------------------

[](#️-server-side-control-liveresponse)

Control client UI directly from your PHP controllers:

```
namespace App\Controllers;

use Switch\Live\LiveResponse;

class UserController
{
    public function update()
    {
        // 1. Trigger Floating Toast Notification ('success', 'error', 'warning', 'info')
        LiveResponse::toast('Profile updated successfully!', 'success');

        // 2. Dispatch Custom JavaScript Event
        LiveResponse::emit('user-updated', ['userId' => 42]);

        // 3. Trigger Seamless SPA Redirect
        LiveResponse::redirect('/dashboard');

        // 4. Dynamically Set Page Title or Target Container
        LiveResponse::title('User Profile — Switch');
        LiveResponse::target('#profile-container');

        // 5. Preserve Scroll Position
        LiveResponse::preserveScroll(true);

        return view('partials.profile-card', ['user' => $user]);
    }
}
```

---

📡 Client-Side JavaScript Events
-------------------------------

[](#-client-side-javascript-events)

Listen for lifecycle events in your custom JavaScript scripts:

```
// Before navigation starts
document.addEventListener('switch:live:start', (e) => {
    console.log('Navigating to:', e.detail.url);
});

// After DOM update succeeds
document.addEventListener('switch:live:success', (e) => {
    console.log('Successfully updated:', e.detail.url);
});

// When an error occurs
document.addEventListener('switch:live:error', (e) => {
    console.error('Request failed:', e.detail);
});

// Request lifecycle complete
document.addEventListener('switch:live:finish', (e) => {
    console.log('Finished navigation.');
});
```

---

🧪 Testing
---------

[](#-testing)

Run the test suite with PHPUnit:

```
composer test
```

---

📄 License
---------

[](#-license)

The Switch Live package is open-source software licensed under the [MIT license](LICENSE).

###  Health Score

21

—

LowBetter than 17% of packages

Maintenance65

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/68065074?v=4)[Celio Natti](/maintainers/celionatti)[@celionatti](https://github.com/celionatti)

---

Top Contributors

[![celionatti](https://avatars.githubusercontent.com/u/68065074?v=4)](https://github.com/celionatti "celionatti (7 commits)")

### Embed Badge

![Health badge](/badges/switch-live/health.svg)

```
[![Health](https://phpackages.com/badges/switch-live/health.svg)](https://phpackages.com/packages/switch-live)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
