PHPackages                             shinsenter/defer.php - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. shinsenter/defer.php

AbandonedArchivedLibrary[Utility &amp; Helpers](/categories/utility)

shinsenter/defer.php
====================

🚀 A PHP library that focuses on minimizing payload size of HTML document and optimizing processing on the browser when rendering the web page.

2.5.0(2y ago)4110.1k↓70%61MITPHPPHP ^5.6 || ^7.0 || ^8.0

Since Mar 19Pushed 2y ago1 watchersCompare

[ Source](https://github.com/shinsenter/defer.php)[ Packagist](https://packagist.org/packages/shinsenter/defer.php)[ GitHub Sponsors](https://code.shin.company/defer.php/stargazers)[ Patreon](https://www.patreon.com/appseeds)[ RSS](/packages/shinsenter-deferphp/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (10)Dependencies (9)Versions (31)Used By (1)

defer.php
=========

[](#deferphp)

🚀 A PHP library that aims to help you concentrate on web performance optimization.

- **Package**: [@shinsenter/defer.php](https://packagist.org/packages/shinsenter/defer.php)
- **Version**: 2.5.0
- **Author**: Mai Nhut Tan
- **Copyright**: 2019-2023 SHIN Company
- **License**: [MIT](https://raw.githubusercontent.com/shinsenter/defer.php/master/LICENSE)

[![GitHub](https://camo.githubusercontent.com/be3db8b044df1df0ccf490cf7a1fe08b50d426000191a791bc9c0b1a1cf787d8/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7368696e73656e7465722f64656665722e7068702e737667)](https://code.shin.company/defer.php)[![GitHub Release Date](https://camo.githubusercontent.com/0eb2216b3397513372fe8cbd65f773f52b54597509c921320573d8eba8f0c3af/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652d646174652f7368696e73656e7465722f64656665722e7068702e737667)](https://code.shin.company/defer.php/releases)[![CodeFactor Grade](https://camo.githubusercontent.com/9fff7673d95473206c337943ff7a78e99141b4ecbf0206b65688ce709fbe220c/68747470733a2f2f696d672e736869656c64732e696f2f636f6465666163746f722f67726164652f6769746875622f7368696e73656e7465722f64656665722e706870)](https://www.codefactor.io/repository/github/shinsenter/defer.php)[![Post an issue](https://camo.githubusercontent.com/9e93e892d0685e1bf7a1d0bd7c8410d6ecf2086a0a7b48dd58a6b96fa556ea2a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f6e747269627574696f6e732d77656c636f6d652d627269676874677265656e2e7376673f7374796c653d666c6174)](https://code.shin.company/defer.php/issues)[![GitHub issues](https://camo.githubusercontent.com/4ab4978d175a913e2a6ece034f6f19df8ff97da35e4d93b50c6eaec7656bcf86/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732d7261772f7368696e73656e7465722f64656665722e7068702e737667)](https://code.shin.company/defer.php/issues/new)

---

🥇 Powered by [defer.js](https://code.shin.company/defer.js) - A super small, super efficient library that helps you lazy load almost everything like images, video, audio, iframes as well as stylesheets, and JavaScript.

---

Features
--------

[](#features)

- Simplify library options
- Embed defer.js library
- Normalize DOM elements
- Fix missing meta tags
- Fix missing media attributes
- Preconnect to required origins
- Preload key requests
- Prefetch key requests
- Browser-level image lazy-loading for the web
- Lazy-load offscreen and hidden iframes
- Lazy-load offscreen and hidden videos
- Lazy-load offscreen and hidden images
- Lazy-load CSS background images
- Reduce the impact of JavaScript
- Defer non-critical CSS requests
- Defer third-party assets
- Add fallback `` tags for lazy-loaded objects
- Add custom HTML while browser is rendering the page (splashscreen)
- Attribute to ignore optimizing the element
- Attribute to ignore lazyloading the element
- Optimize AMP document
- Minify HTML output

Installation
------------

[](#installation)

### Install with composer

[](#install-with-composer)

```
composer require shinsenter/defer.php
```

### Load the library into your program

[](#load-the-library-into-your-program)

```
// Include the library
require_once __DIR__ . '/vendor/autoload.php';

// TODO: your code is from here
```

### Requirements

[](#requirements)

This library requires PHP 5.6 or above so you need this version or the latest version of PHP installed on your system.

It recommends that the server is running PHP version 7.3+ or above for better performance and supports.

Library options from v2.x are not backward compatible with previous release's options. Please read [library manual](#options) for more details.

Usages
------

[](#usages)

### Basic usage

[](#basic-usage)

```
// Include the library
require_once __DIR__ . '/vendor/autoload.php';

// Create a Defer object
$defer = new \AppSeeds\Defer();

// Read HTML source from file
$html_source = file_get_contents('mypage.html');

// Then get the optimized output
$result = $defer->fromHtml($html_source)->toHtml($html);
var_dump($result);

// You can use the same instance to keep loading another HTML and optimize it
$result2 = $defer->fromHtml(file_get_contents('otherpage.html'))->toHtml();
var_dump($result2);
```

### Options

[](#options)

```
// Include the library
require_once __DIR__ . '/vendor/autoload.php';

// Declare the options
$options = [
  // Insert debug information inside the output HTML after optimization.
  // Debug information will contain outer HTMLs of tags before being optimized.
  // Default: false (turn off the debug information)
  'debug_mode' => false,

  // Although defer.js is the soul of this library,
  //   in some regions, you may want to serve defer.js library locally
  //   due to The General Data Protection Regulation (EU).
  // See: https://en.wikipedia.org/wiki/General_Data_Protection_Regulation
  // If you need to manually insert the defer.js library yourself,
  //   please enable this option to true.
  // Default: false (always automatically insert defer.js library)
  'manually_add_deferjs' => false,

  // URL to defer.js javascript file.
  // Default: https://cdn.jsdelivr.net/npm/@shinsenter/defer.js@3.6.0/dist/defer_plus.min.js
  'deferjs_src'  => \AppSeeds\DeferConstant::SRC_DEFERJS_CDN,

  // URL to javascript contains fixes.
  // for some older browsers that do not support IntersectionObserver feature.
  // Default: https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserver
  'polyfill_src' => \AppSeeds\DeferConstant::SRC_POLYFILL_CDN,

  // Inline the defer.js library to minimize download time in the browser.
  // Default: true (always automatically inline defer.js library)
  'inline_deferjs' => true,

  // ---------------------------------------------------------------------------

  // This option moves all stylesheets to bottom of the head tag,
  //   and moves script tags to bottom of the body tag
  // See: https://web.dev/render-blocking-resources/
  // Default: true (always automatically fix render blocking)
  'fix_render_blocking' => true,

  // Turn on optimization for stylesheets
  // This option applies to style and link[rel="stylesheet"] tags.
  // Best practices: https://web.dev/extract-critical-css/
  // Default: true (automatically optimize stylesheets)
  'optimize_css'        => true,

  // Optimize script tags (both inline and external scripts).
  // Note: The library only minify for inline script tags.
  // See: https://web.dev/unminified-javascript/
  // Default: true (automatically optimize script tags)
  'optimize_scripts'    => true,

  // Optimize img, picture, video, audio and source tags.
  // See: https://web.dev/browser-level-image-lazy-loading/
  // See: https://web.dev/lazy-loading-images/
  // Default: true (automatically optimize)
  'optimize_images'     => true,

  // Optimize iframe, frame, embed tags.
  // See: https://web.dev/lazy-loading-video/
  // Default: true (automatically optimize)
  'optimize_iframes'    => true,

  // Optimize tags that containing CSS for loading images from external sources.
  // For example, style properties contain background-image:url() etc.
  // See: https://web.dev/optimize-css-background-images-with-media-queries/
  // Default: true (automatically optimize)
  'optimize_background' => true,

  // Create noscript tags so lazy-loaded elements can still display
  //   even when the browser doesn't have javascript enabled.
  // This option applies to all tags that have been lazy-loaded.
  // See: https://web.dev/without-javascript/
  // Default: true (automatically create fallback noscript tags)
  'optimize_fallback'   => true,

  // Optimize anchor tags, fix unsafe links to cross-origin destinations
  // See: https://web.dev/external-anchors-use-rel-noopener/
  // Default: true (automatically optimize)
  'optimize_anchors' => true,

  // Add missing meta tags such as meta[name="viewport"], meta[charset] etc.
  // See: https://web.dev/viewport/
  // Default: true (automatically optimize)
  'add_missing_meta_tags' => true,

  // Preconnect to required URL origins.
  // See: https://web.dev/uses-rel-preconnect/
  // Default: true (automatically optimize)
  'enable_dns_prefetch'   => true,

  // Preload key requests such as stylesheets or external scripts.
  // See: https://web.dev/uses-rel-preload/
  // Default: false (do not apply by default)
  'enable_preloading'     => false,

  // Lazy-load all elements like images, videos when possible.
  // See: https://web.dev/lazy-loading/
  // Default: true (automatically optimize)
  'enable_lazyloading'    => true,

  // Minify HTML output.
  // See: https://web.dev/reduce-network-payloads-using-text-compression/
  // Default: false (do not minify HTML by default)
  'minify_output_html'    => false,

  // ---------------------------------------------------------------------------

  // Detect and optimize third-party URLs if possible (experiment).
  // This option also allows entering an array containing the URL origins to be defered.
  // See: https://web.dev/preload-optional-fonts/
  // Default: true (automatically optimize)
  'defer_third_party' => true,

  // Apply fade-in animation to tags after being lazy-loaded.
  // Default: false (do not apply by default)
  'use_css_fadein_effects' => false,

  // Use random background colors for images to be lazy-loaded.
  // Set the value to 'grey' if you want to use greyish background colors.
  // Default: false (do not apply by default)
  'use_color_placeholder'  => false,

  // ---------------------------------------------------------------------------

  // Default placeholder for lazy-loaded img tags.
  // If this value is not set or empty,
  //   an SVG image will be used to avoid CLS related problems.
  // See: https://web.dev/cls/
  // Default: blank string
  'img_placeholder'    => '',

  // Default placeholder for lazy-loaded iframe tags.
  // Default: 'about:blank'
  'iframe_placeholder' => 'about:blank',

  // ---------------------------------------------------------------------------

  // Show custom HTML content (splashscreen)
  //   while browser is rendering the page (experiment).
  // Default: blank string (no splashscreen)
  'custom_splash_screen' => '',

  // ---------------------------------------------------------------------------

  // Do not lazy-load for URLs containing
  //   one of the array's texts (exact match keywords).
  // Default: blank array
  'ignore_lazyload_paths'  => [],

  // Do not lazy-load for tags containing
  //   one of the array's texts (exact match keywords).
  // Default: blank array
  'ignore_lazyload_texts'  => [],

  // Do not lazy-load for tags containing one of these CSS class names.
  // Default: blank array
  'ignore_lazyload_css_class'  => [],

  // Do not lazy-load for tags matching one of these CSS selectors.
  // See: https://www.w3schools.com/cssref/css_selectors.asp
  // Default: blank array
  'ignore_lazyload_css_selectors'  => [
    // 'header img',
    // 'img#logo',
  ],
];

// Create a Defer object
$defer  = new \AppSeeds\Defer($options);
$result = $defer->fromHtml(file_get_contents('mypage.html'))->toHtml();
var_dump($result);

// Change library options
$defer->options()->debug = true;
$defer->options()->minify_output_html = true;

// Keep loading another HTML and optimize it with new options
$result2 = $defer->fromHtml(file_get_contents('otherpage.html'))->toHtml();
var_dump($result2);
```

### Optimize final output HTML of a website

[](#optimize-final-output-html-of-a-website)

You also can capture the final output generated by PHP and optimize it before giving it back to browser.

```
// Include the library
require_once __DIR__ . '/vendor/autoload.php';

// Create a callback function
function ob_deferphp($html) {
  // Create a Defer object
  $defer = new \AppSeeds\Defer([
    /* declare options here */
  ]);

  return $defer->fromHtml($html)->toHtml();
}

// Call ob_start() function to create an output buffer
//   and pass above callback function name as its argument.
// This function should be called before any other process to print the content.
ob_start('ob_deferphp');

// .......... (place your PHP code here)

// And call this to flush optimized output HTML
//   right before you send the final HTML to browser.
ob_end_flush();
```

### Ignore optimization for some elements

[](#ignore-optimization-for-some-elements)

Add an `data-ignore` attribute to element that you don't want it to be optimized by the library. This attribute can be used for all HTML elements.

```

var MY_IMPORTANT_VARIABLE = 'important value';

```

Add an `data-nolazy` attribute to element that you don't want it to be lazy-loaded by the library. Other optimizations for that element will still be applied except lazy-load. This attribute can be used for all ``, ``, ``, ``, `` and also `` elements.

```

```

### Stylesheets and JavaScript

[](#stylesheets-and-javascript)

This library supports a more efficient lazy-load method for stylesheets and JavaScript tags that contain the `defer` attribute.

```

someHeavyTask();
```

Even when the library is turned off, above tags that contain `defer` attribute are backwards compatible and work well in most modern browsers. You can use it with peace of mind.

### AMP page

[](#amp-page)

Only few options of this library are applicable to AMP pages (minifying HTML content for example).

My works
--------

[](#my-works)

### Defer.js

[](#deferjs)

🥇 A super small, super efficient library that helps you lazy load almost everything like images, video, audio, iframes as well as stylesheets, and JavaScript.

### Wordpress plugin

[](#wordpress-plugin)

⚡️ A native, blazing fast lazy loader. ✅ Legacy browsers support (IE9+). 💯 SEO friendly. 🧩 Lazy-load everything.

### Laravel package

[](#laravel-package)

🚀 A Laravel package that focuses on minimizing payload size of HTML document and optimizing processing on the browser when rendering the web page.

Support my activities
---------------------

[](#support-my-activities)

[![Donate via Paypal](https://camo.githubusercontent.com/59139f7fde490eae3d203615321dc6ee3d41c9599f06afc3667ddc913d4a1f24/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f446f6e6174652d50617970616c2d626c7565)](https://www.paypal.me/shinsenter)[![Become a sponsor](https://camo.githubusercontent.com/8c323dbd0c7206991369959ac65c25373980644776706cf1dcdb40aa201b7e79/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f446f6e6174652d50617472656f6e2d6f72616e6765)](https://www.patreon.com/appseeds)[![Become a stargazer](https://camo.githubusercontent.com/c3d629f1a2eb6635b8aeb6df94411bc452f17d5f24ae5b02223cd39dc893a176/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f537570706f72742d5374617267617a65722d79656c6c6f77)](https://code.shin.company/defer.php/stargazers)[![Report an issue](https://camo.githubusercontent.com/5e252293540c18d3e8c661240a7efcee4d63aabb780fb442c00e356b69056432/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f537570706f72742d4973737565732d726564)](https://code.shin.company/defer.php/issues/new)

---

From Vietnam 🇻🇳 with love.

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity35

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity76

Established project with proven stability

 Bus Factor1

Top contributor holds 98.3% 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.

###  Release Activity

Cadence

Every ~58 days

Recently: every ~218 days

Total

29

Last Release

1020d ago

Major Versions

1.1.1 → 2.0.02021-03-25

PHP version history (3 changes)1.0.0PHP ^5.6

1.0.7PHP &gt;=5.6

1.1.1PHP ^5.6 || ^7.0 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/5c8b809d5ee939678c993eab96c03e8481edd09992d8455eab87c2c134fdbb7d?d=identicon)[shinsenter](/maintainers/shinsenter)

---

Top Contributors

[![shinsenter](https://avatars.githubusercontent.com/u/2082119?v=4)](https://github.com/shinsenter "shinsenter (117 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (1 commits)")[![mnakalay](https://avatars.githubusercontent.com/u/1488833?v=4)](https://github.com/mnakalay "mnakalay (1 commits)")

---

Tags

avoid-render-blockingbrowser-compatibilitybrowser-perfcomposer-packagedefer-jsefficientintersection-observerlazy-adslazy-csslazy-iframelazy-imagelazy-imglazy-jslazy-loaderlazy-loadinglazy-videolazyloadpagespeedperformantwebsite-performancelazy loadingpage-speedPHP LibrarydeferlazyloadHTML minifyPageSpeeddefer.phplazyload imagelazyload videolazyload fontlazyload jslazyload cssloading lazyspeed optimizationgtmetrixlazyload wordpresslazyload facebooklazyload youtubeavoid render blockingdom optimizationsite performance

###  Code Quality

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/shinsenter-deferphp/health.svg)

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

###  Alternatives

[friendsofphp/php-cs-fixer

A tool to automatically fix PHP code style

13.5k245.4M23.9k](/packages/friendsofphp-php-cs-fixer)[symfony/form

Allows to easily create, process and reuse HTML forms

2.8k158.7M3.3k](/packages/symfony-form)[symfony/rate-limiter

Provides a Token Bucket implementation to rate limit input and output in your application

27051.7M254](/packages/symfony-rate-limiter)[helsingborg-stad/municipio

A bootstrap theme for creating municipality sites.

4028.3k10](/packages/helsingborg-stad-municipio)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

84735.1k](/packages/flow-php-flow)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.4M514](/packages/shopware-core)

PHPackages © 2026

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