• Stars
    star
    157
  • Rank 238,399 (Top 5 %)
  • Language
    HTML
  • Created over 8 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

My 10K apart entry - A handy 1KB script that decides the leanest image format to return based on your browser.

Image Beast

The Image Beast - 10K Apart Entry

From the murky depths of the sea, comes the image beast! It’s here to tame your every image need with a handy 1 KB script. There are so many great different image formats available these days, and many of them offer significant file size savings over the traditional formats (JPEG, GIF, PNG). Unfortunately not every browser provides support for all of these great image formats. We want to pass on these savings to all of our users.

This is where the image beast comes in! Simply include this tiny 1KB script in your Service Worker, create the appropriate image formats, and it will handle the rest for you.

Serve the lightest, leanest images to your users and help them get the fastest page load times possible. Grrrrrr! The image beast does all of these things:

  • Serves WebP images to Google’s Chrome Browser
  • Serves JpegXR images to Microsoft’s Edge Browser
  • Serves lean images to Android users with the Data Saver feature enabled
  • Caches the images!

Progressive Enhancement

What about older browsers I hear you say? Well, the beast has them tamed too! Service Workers are the ultimate progressive enhancement and if your browser doesn’t support them they will simply return the original images as normal. If your browser does support Service Workers, then the image beast simply uses it slippery tentacles to decide the perfect image format to return.

WebP? JPEGXR? Or even a low resolution version of an image? The image beast is in control.

Show me an example!

First up, you need to check if Service Workers are supported in your browser. If they are, create and register the Service Worker by adding the following code to your page.

<script>
 // Register the service worker
 if ('serviceWorker' in navigator) {
 navigator.serviceWorker.register('./service-worker.js').then(function(registration) {
   // Registration was successful
   console.log('ServiceWorker registration successful with scope: ', registration.scope);
 })
 }
</script>

Next, simply import the script into your Service Worker (service-worker.js) and begin optimizing.

(global => {
  'use strict';

  importScripts('./imagebeast.min.js');
  optimize({ useWebp: false, useXr: true, useSaveData: true, useCache: true });

  // Ensure that our service worker takes control of the page as soon as possible.
  global.addEventListener('install', event => event.waitUntil(global.skipWaiting()));
  global.addEventListener('activate', event => event.waitUntil(global.clients.claim()));
})(self);

As you can see from the code above, you can also configure image beast. For example, if you’d prefer not to return WebP images, then simply disable it in the config.

If you’d like to see this in action, head over to deanhume.github.io/image-beast for a working example.

How does it work under the hood?

The image beast works by listening to the client hints that your browser sends through when it makes an HTTP request. Let's say you are using Google Chrome as your browser. By default, the browser will send through an Accept Request header and in the case of Chrome, it will send through a client hint of "image/webp" notifying the server that it supports WebP images. Using a Service Worker, we can tap into this request and return an alternate version of the image.

Hey, but I don't use Google Chrome! Don't worry - the image beast has you covered. Microsoft's Edge currently has Service Workers under development and the image beast will return JPEGXR images for you if it detects that it can support it. The image beast is prowling and ready to pounce on every image format.

Performance is key!

Using the image beast, you are able to return the leanest possible images to your user's browser. Using the power of Service Workers, we can take this a step further and cache the image request once it has been made. This means that the user won't even have to make another HTTP request for the image and it will load instantly. It is built-in by default, but you can turn it off using the configuration options.

The image beast also has another sneaky trick up it's tentacle. Users that use Android devices and have the Data Saver feature enabled for their phone or tablet will have low resolution images returned to them. All you need to do is save a low resolution version of the image with "-savedata" appended to the file name (eg. beast-savedata.jpg) and the image beast will do the rest. In fact, even if you haven't provided a low resolution version of the image, it will simply return a tiny placeholder image in order to save your users data.

More Repositories

1

typography

A collection of web typography resources
634
star
2

progressive-web-apps-book

All of the code for "Progressive Apps" - a book by Dean Hume
HTML
303
star
3

pwa-update-available

Service Workers - New Update Available sample
HTML
254
star
4

lazy-observer-load

A library to lazy load images using Intersection Observer
JavaScript
244
star
5

pwa-tips-tricks

A big list of Progressive Web App tips & tricks!
137
star
6

html-minifier

A simple command line tool to minify your HTML, Razor views & Web Forms views
C#
134
star
7

beer

The source code for the Progressive Beer app!
JavaScript
74
star
8

Service-Worker-Offline

A really, really simple offline page using Service Workers
JavaScript
50
star
9

streams

Experimenting with the Streams spec
JavaScript
31
star
10

ImageOptimizer

A collection of image optimization techniques
C#
28
star
11

Service-Workers-BackgroundSync

A simple example using Service Workers & Background Sync
HTML
26
star
12

SignalRUsersOnline

Get the count of users online using SignalR
23
star
13

pwa-connection-type

A tiny service worker script to change image quality dependant on connection type (2G, 3G, etc)
JavaScript
23
star
14

Service-Workers-HTTP2-Push

An example using HTTP/2 push and Service Workers to achieve super fast load times
JavaScript
22
star
15

firebase-example

A simple firebase site example
HTML
11
star
16

FastASPNetWebsites

The source code for the Fast ASP.NET websites book
PowerShell
11
star
17

Service-Workers-WebP

A simple example using HTTP Client Hints and Service Worker
HTML
10
star
18

Service-Workers-Fetch-Timeout

A simple example using timeouts and service workers
JavaScript
9
star
19

pwa-cloudinary

JavaScript
6
star
20

ambient-light-sensor

Experimenting with the Ambient Light Sensor in Chrome
HTML
6
star
21

speedindex-test

A example page that demos the https://github.com/WPO-Foundation/RUM-SpeedIndex library
JavaScript
5
star
22

http2-test

A simple test example to run HTTP2
JavaScript
4
star
23

Service-Worker-Toolbox

A demo repo using the Service Worker Toolbox
JavaScript
4
star
24

buildingstartupteams.com

The code repo for buildingstartupteams.com
HTML
3
star
25

web-share

A playground for the Web Share API
HTML
3
star
26

UpFrontConf

A site optimization example
HTML
2
star
27

real-performance-metrics

A basic performance tracker that measures first paint, first contentful paint, and time to interactive.
JavaScript
2
star
28

daily-dashboard

A daily dashboard for home use.
JavaScript
1
star
29

settled

A protoype messaging / booking application for Settled
JavaScript
1
star
30

CodeGenerateMe

The source code for the website - codegenerate.me
C#
1
star
31

SmushMySite

SmushMySite is an image optimization tool that takes advantage of the Yahoo Smush.itâ„¢ service. It is a quick and easy way to optimize all images on webpage, or all images on your site. It is developed in C# and WPF.
C#
1
star