Speed Kit 1.14.0

Baqend Speed Kit accelerates your existing website by rerouting the requests through Baqend's caching infrastructure. Thereby you gain a remarkable boost of performance to your website.

See Release Notes

Download

Use the following links to download version 1.14.0 of Speed Kit.

  • Service Worker

    The Service Worker needs to be served from your website under the root directory, i.e. https://www.example.org/sw.js.

    Download sw.js
  • Snippet

    Use the snippet in your site to enable and configure Speed Kit. It needs to be included into your page.

    Download snippet.js
  • Dynamic Fetcher

    Use the snippet in your site to handle Dynamic Blocks. It needs to be included into your page when you use Dynamic Blocks, e.g. for personalized or segmented content.

    Download dynamic-fetcher.js

Configuration

After you have downloaded and installed Speed Kit, you have to configure and fine-tune it to your needs.

If you are using WordPress, you can therefor simply use our WordPress plugin for Speed Kit. It is a one click solution and very easy to setup with your existing WordPress site!

For all other systems, you have to embed the snippet into your HTML and define a speedKit variable.

Take the following example:


              <!DOCTYPE html>
              <html>
                <head>
                  <!-- ... -->
            
                  <script>
                    var speedKit = {
                      appName: 'my-speed-kit-app', // Your app on Baqend
                      whitelist: [
                        // Only apply Speed Kit on URLs whose pathname starts with "/assets"
                        { pathname: '/assets' }
                      ],
                      blacklist: [
                        // Only blacklist URLs which match the regular expression "/content/" and
                        // are HTML documents
                        { url: /content/, contentType: ['document'] }
                      ]
                    };
                    // ... embed the snippet here ...
                  </script>
                </head>
                <body> <!-- ... --> </body>
              </html>
            

Then, you can include the snippet which takes the speedKit variable and enables the ServiceWorker.

You can find all options for the speedKit variable in the SpeedKitConfig interface.

Dynamic Blocks

If you have personalized or segmented content, you want to use dynamic blocks. To use them, you need to include another snippet, the Dynamic Fetcher, into your HTML above your Speed Kit config. Then, you can adjust the Dynamic Fetcher with the dynamicBlockConfig variable.

Take the following example:


              var dynamicBlockConfig = {
                blockSelector: '.dynamic-block',
                tagAttribute: 'data-block-id',
                statusClass: 'speed-kit',
                forceFetch: true,
              };
              // ... embed the Dynamic Fetcher here ...
            

After your config you can include the Dynamic Fetcher snippet which will take the dynamicBlockConfig variable.

You can find all options for the dynamicBlockConfig variable in the DynamicBlockConfig interface.

DynamicBlockConfig

Add the following properties to your dynamicBlockConfig variable.

blockSelector

The query selector to identify dynamic blocks.

You can use CSS classes or any other query selector.

Allowed values: string

Default value: ".speed-kit-dynamic"

customMergeFunction

advanced Custom function to merge dynamic blocks into the DOM.

Defines a custom function to merge a dynamic block loaded from the origin with its cached counterpart. The default merge function simply swaps the local for the remote block.

Allowed values: (localBlock: HTMLElement, remoteBlock: HTMLElement) ⇒ void

Default value: (localBlock, remoteBlock) => localBlock.outerHTML = remoteBlock.outerHTML

forceFetch

advanced Forces to always fetch the origin's version of the HTML.

Option to check for Dynamic Blocks in the HTML before requesting the dynamic data. If false, the origin's HTML will only be fetched when Dynamic Blocks are detected. If true, the origin's HTML will be fetched right away (faster).

Allowed values: boolean

Default value: true

requestTransformFunction

advanced Function to transform dynamic block request sent to origin.

Defines a custom function that is applied to the origin request used to fetch the personalized page which is used to switch out the Dynamic Blocks.

Allowed values: (request: Request) ⇒ Request

Default value: (request) => request

runOnFirstLoad

advanced Enables the Dynamic Fetcher regardless the status of the Service Worker.

Option to execute the Dynamic Fetcher on first load or not. If false, the Dynamic Fetcher will only be executed when the Service Worker is active. If true, the Dynamic Fetcher will be executed on first load.

Allowed values: boolean

Default value: false

statusClass

The prefix of the status HTML classes, which will be attached to the HTML tag.

For example, you can use these classes to hide Dynamic Blocks before their content has been replaced.

The classes that will be attached to the HTML element are:

  • < statusClass >-loading will be appended before the Dynamic Blocks are replaced for the actual content.
  • < statusClass >-loaded will be appended after the Dynamic Blocks have been replaced.

Allowed values: string

Default value: "speed-kit-dynamic"

tagAttribute

The tag attribute to get a unique block id from.

You can also supply a custom function to generate an id from the dynamic block that is given as an input parameter.

Each Dynamic Block needs a unique ID in order to be replaced with the right content. This tag attribute is where the Dynamic Fetcher can find this ID. You can use data attribute or just element IDs for example. If a dynamic block has no such attributes and you cannot add them, you can use a custom function to generate a unique id from the dynamic block as an input value.

Allowed values: string | (elem: HTMLElement) ⇒ string

Default value: "data-speed-kit-id"

SpeedKitConfig

Add the following properties to your speedKit variable.

appDomain

advanced The domain to connect to your Baqend app.

Allowed values: string

Example value: speed-kit.example.org

appName

required The name of your Baqend app.

Allowed values: string

blacklist

Some rules for requests which should not be intercepted.

Using an empty rule array means that Speed Kit is blacklisted for no resource (this is the default).

Allowed values: SpeedKitRule[]

Default value: []

Example value: [{ url: /robots\.txt$/, contentType: ["document"] }]

criticalResources (since 1.11.0)

Rules to identify critical resources of an HTML document.

You can use an array of ResourceRules to tell Speed Kit which are the critical resources of specific pages that should be handled with higher priority.

The config looks for example like this:


                var speedKit = {
                  // ... other options ...
                  criticalResources: [{
                    // apply specific critical resources for different pages
                    enabledOn: [{ pathname: ["index.html"] }],
                    resources: ["/assets/picture.jpg"],
                  }, {
                    // global critical resources
                    resources: ["/assets/logo.png"],
                  }],
                  // ... other options ...
                };
                

You can also just pass an array of strings to globally define critical resources for all pages of your site:


                var speedKit = {
                  // ... other options ...
                  criticalResources: ["/assets/logo.png"],
                  // ... other options ...
                };
                

Allowed values: (string | ResourceRule)[]

Default value: []

Example value: [{ enabledOn: [{ pathname: ["index.html"] }], resources: ["/assets/logo.png"] }]

delayed (since 1.10.0)

Some rules for requests which should be intercepted but delayed.

Delayed resources improve the critical rendering path of your website. Using an empty rule array means that Speed Kit delays no resources (this is the default).

Allowed values: SpeedKitRule[]

Default value: []

Example value: [{ url: 'www.googletagmanager.com/gtm.js' }]

Speed Kit will delay the Google Tag Manager request to speed up all render-critical requests.

disableCache

advanced Disables using the ServiceWorker cache.

Allowed values: boolean

Default value: false

disabled

Whether to disable the service worker on this page.

Allowed values: boolean

Default value: false

enabledSites (since 1.1.1)

Rules to identify html sites on which Speed Kit should be enabled.

Using an empty rule array means that Speed Kit is enabled on every site.

Allowed values: SpeedKitRule[]

Default value: []

Example value: [{ url: /^www\.baqend\.com\/speedkit\//}]

fetchOriginInterval (since 1.2.0)

An interval in which Speed Kit will call the original document, e.g., to receive its cookies.

In order to update your client's cookies or renew the user session, Speed Kit is able to tee document requests so user-specific Set-Cookie headers are asynchronously fetched from your originating backend and applied in the browser.

The following values are allowed:

ValueDescription
–1Do not tee the request (costs least bandwidth of your origin) – default.
0Always tee the request (costs most bandwidth of your origin).
X > 0Tee the request at most every X seconds (saves bandwidth of your origin).

Allowed values: number

Default value: -1

Example value: 60

The request will only be teed against your origin backend when the last call has not been made more than one minute ago.

image (since 1.5.0)

Applies optimizations to images served by Speed Kit.

You can use an array of ImageRules to tell Speed Kit how images should be handled. The config looks for example like this:


                var speedKit = {
                  // ... other options ...
                  image: [
                    {
                      // apply options to images under "/images/teasers/"
                      rules: [{ "pathname": "/images/teasers/" }],
                      options: {
                        quality: 95,
                        downscale: true,
                      },
                    }, {
                      // apply options to images under "/images/photos/"
                      rules: [{ "pathname": "/images/photos/" }],
                      options: {
                        quality: 75,
                        webp: false,
                      },
                    }, {
                      // default options
                      options: {
                        quality: 65,
                        webp: true,
                        downscale: false,
                      },
                    },
                  ],
                  // ... other options ...
                };
                

All images which are not matched by a rule will be applied with the default options (see ImageOptions).

You can also just pass an object of ImageOptions to this option if you want to override the defaults globally:


                var speedKit = {
                  // ... other options ...
                  image: {
                    quality: 95, // change default quality from 85% to 95%
                    webp: false, // disable WebP support which is enabled by default
                  },
                  // ... other options ...
                };
                

Allowed values: ImageOptions | ImageRule[]

Example value: [{ rules: [{ "pathname": "/assets/img/" }], options: { quality: 65, downscale: true } }]

In this example, Speed Kit will compress all images under the "/assets/img/" path with a quality of 65% and limit its size to the user's screen. All other images will not be manipulated at all.

maxStaleness (deprecated)

advanced The refresh interval of the Bloom filter in milliseconds.

Deprecated: Use <a href="#SpeedKitConfig-refreshInterval">SpeedKitConfig.refreshInterval</a> (in seconds) instead.

Allowed values: number

Default value: 300000

navigationPreload

advanced Enables Navigation Preloads.

To learn more about Navigation Preloads read Google's Developer Blog.

Note: This should only be enabled when document requests are not served through Speed Kit, i.e. they are blacklisted. With this option enabled, all navigate requests are served by the origin server and will not be cached.

Allowed values: boolean

Default value: false

preloadBloomFilter

advanced Load the Bloom filter when activating Speed Kit.

Allowed values: boolean

Default value: true

reconnectInterval (since 1.1.0)

advanced The interval in which to try to reconnect to the disconnected Baqend app in milliseconds.

Allowed values: number

Default value: 60000

refreshInterval

advanced The refresh interval of the Bloom filter in seconds.

This option specifies the interval to refresh the Bloom filter, which is a cache sketch of changed resources on the server side. This interval effectively decides the maximum staleness of assets on your site.

Allowed values: number

Default value: 300

Example value: 300

Every 5 minutes, Speed Kit will synchronize the Bloom filter with the next request handles.

relativeModuleImports (since 1.13.0)

advanced Whether relative imports are used for JavaScript modules.

Allowed values: boolean

Default value: false

scope

advanced The Scope under which Speed Kit will be active.

Allowed values: string

Default value: "/"

staleWhileRevalidate

advanced A timespan in seconds in which the outdated Bloom filter may be temporarily used.

The user session length in seconds in which the Bloom filter is used to decide the staleness of HTML cache entries while being refreshed in the background. This setting increases cache hits for HTML files drastically and should represent the length of your users' sessions.

Allowed values: number

Default value: 1800

Example value: 1800

If the Bloom filter is outside its refresh interval, Speed Kit can use the outdated Bloom filter once for an additional timespan of 30 minutes to take content from the cache while updating the Bloom filter in the background.

stripQueryParams (since 1.10.0)

A set of rules to match against query parameters to be stripped from requested URLs.

Every before they are fetched.

Allowed values: Condition

Default value: null

Example value: ['analytics', 'gclid']

Speed Kit will remove “analytics” and “gclid” query parameters before issuing and caching the request.

sw

advanced Location of the service worker.

Allowed values: string

Default value: "/sw.js"

userAgentDetection

Enables user agent detection to handle mobile and desktop differently.

When user agent detection is enabled, Speed Kit distinguishes requests between mobile and desktop. Only activate this feature if you serve different assets for mobile and desktop users because it reduces your cache hit ratio.

Allowed values: boolean

Default value: false

whitelist

Some rules for requests which should be intercepted.

Using an empty rule array means that Speed Kit is whitelisted for every resource (this is the default).

Allowed values: SpeedKitRule[]

Default value: []

Example value: [{ pathname: "/assets" }]

ResourceRule

A resource rule selects a subset of critical resources.

enabledOn (since 1.11.0)

The pages from which the critical resources should be fetched.

Allowed values: SpeedKitRule[]

Example value: [{ host: "www.baqend.com" }]

In this example, Speed Kit will fetch the critical resources given by the resources property for the given page.

resources (since 1.11.0)

required The critical resources to fetch before any other resources.

Allowed values: string[]

Example value: ["https://www.baqend.com/style.css"]

In this example, Speed Kit will fetch the "style.css" file with high priority.

ImageRule

An image rule selects a subset of images and applies some ImageOptions to it. See the image option for more information.

enabledSites (since 1.9.0)

The sites on which this image rule is enabled.

Allowed values: SpeedKitRule[]

Example value: [{ "pathname": "/product/details/" }]

In this example, Speed Kit will apply image options given by the options property to all images requested from a product details page under the path of "/product/details/". All other images will not be affected by this rule.

options (since 1.5.0)

required The options to apply to the selected images.

Allowed values: ImageOptions

Example value: { quality: 75, webp: false }

Applies a quality of 75% and disables WebP support for all images affected by this rule.

rules (since 1.5.0)

The rules to match only some images.

Allowed values: SpeedKitRule[]

Example value: [{ "pathname": "/images/photos/" }]

In this example, Speed Kit will apply image options given by the options property to all images under the "/images/photos/" path. All other images will not be affected by this rule.

ImageOptions

These options can be applied on images. See the image option for more information.

crop (since 1.5.0)

Crops images to the specified dimensions.

This option allows you to crop your images to specific sizes. If you specify a string, you can give an aspect ratio, e.g., "16:9", "4:3". Specify an array of two numbers to smartly crop the image to a specific width and height. If you specify an array of four numbers, the first two values are interpreted as X and Y coordinates and the last two values as width and height. To disable cropping, just specify false.

Allowed values: false | string | [number, number] | [number, number, number, number]

Default value: false

Example value: [20, 10, 200, 400]

Crops a 200 × 400 pixel area from 20 pixels on the X axis and 10 pixels on the Y axis.

downscale (since 1.5.0)

Downscales image dimensions to the user's screen.

This option helps to reduce image file sizes, especially for mobile. If your website delivers images that are larger than the user's display requires, they are automatically scaled down to the screen.

Allowed values: boolean

Default value: true

maxHeight (since 1.8.0)

Downscales images to this maximum height.

If you happen to know the maximum height of an image, you can use this option to tell Speed Kit how much to downscale. This can help to reduce file sizes significantly. If this option is set to false (default), the max width is inferred from the devices screen size. Note: The downscale options must be enabled (default) for this option to take effect.

Allowed values: number | false

Default value: false

maxWidth (since 1.8.0)

Downscales images to this maximum width.

If you happen to know the maximum width of an image, you can use this option to tell Speed Kit how much to downscale. This can help to reduce file sizes significantly. If this option is set to false (default), the max width is inferred from the devices screen size. Note: The downscale options must be enabled (default) for this option to take effect.

Allowed values: number | false

Default value: false

pjpeg (since 1.5.0)

Converts JPEG images to the progressive format.

Progressive JPEG images have a smaller file size and are faster for the browser to load. The format achieves this by saving the image data in ascending quality so that a previous version of the image can be displayed at first. This improves the First Meaningful Paint of your website especially where large JPEG images are used.

Allowed values: boolean

Default value: true

quality (since 1.5.0)

The quality in which images should be returned by Speed Kit.

We are using a lossy compression to speed up the delivery of your images. Under normal circumstances, the default quality of 85% will still result in good looking images.

If you pass a number between 0 and 100 to the option, it will be interpreted as a percentage representing the quality. All images handled by Speed Kit will be delivered with this quality. A value of 100 means no loss in quality.

You can disable the feature completely by setting the option to false.

Allowed values: false | number

Default value: 85

screenSizeFactor (since 1.8.0)

Multiplies screen dimensions with this factor to deliver smaller images.

Because modern mobile screens are massive, this options gives you the opportunity to multiply the screen size with a factor between 0 and 1. This way Speed Kit can request much smaller images and safe bandwidth. Note: The downscale options must be enabled (default) for this option to take effect.

Allowed values: number

Default value: 1

webp (since 1.5.0)

Converts images to the WebP format.

If your user's browser supports the WebP format, your images are automatically converted to this format.

Allowed values: boolean

Default value: true

SpeedKitRule

Use rules in your whitelist and blacklist to describe resource patterns.

contentType

An array of content types to use.

Allowed values: ContentType[]

Example value: ["document", "style", "script", "image"]

Only apply this rule to HTML documents, CSS files, JavaScript files and images.

A condition tested against cookie names.

Use the cookie rule to test if a cookie with a given name exists. The Condition that you pass to this attribute will be matched against all available cookie names and this rule is fulfilled, when there exists at least one cookie with a name which matches that Condition.

Allowed values: Condition

Example value: /^PHPSESSID|JSESSID$/

This rule is fulfilled when there exists a cookie with the name PHPSESSID or JSESSID.

desktop (since 1.5.0)

Only fulfills this rule if sent from desktop.

Allowed values: true

host

A condition to test against the host, e.g. “www.baqend.com”, “www.baqend.com:8443”.

Allowed values: Condition

Example value: /\.com$/

mobile (since 1.5.0)

Only fulfills this rule if sent from a mobile device.

Allowed values: true

pathname

A condition to test against the path name, e.g. “/some/path/here”.

Allowed values: Condition

Example value: /\/robots\.txt$/

tablet (since 1.5.0)

Only fulfills this rule if sent from a tablet.

Allowed values: true

tv (since 1.5.0)

Only fulfills this rule if sent from a TV.

Allowed values: true

url

A condition to test against the whole URL, e.g. “www.baqend.com/some/path#and-fragment-part”.

Allowed values: Condition

Example value: /^www\.baqend\.com\//

ContentType

An enumeration classifying the content of a request.

ValueDescription
"audio"Applies to audio files like MP3, WAV, or OGG.
"document"Applies to HTML documents.
"font"Applies to resources which are fonts.
"image"Applies to resources which are images.
"script"Applies to resources which are JavaScript files.
"style"Applies to resources which are style sheets.
"track"Applies to resources which are subtitle tracks of the WebVTT format.
"video"Applies to resources which are videos.

Condition

Conditions are statements which are tested against strings, they can either be:

  • a String which is treated as a prefix against the given subject,
  • a Regular Expression which is tested against the given subject,
  • or an Array of Conditions for which one of its items has to match agains the subject.

Examples

"hello"The subject has to start with “hello”.
["hello", "world"]The subject has to start with either “hello” or “world”.
/^hello world$/The subject has to start and end with “hello world”.
/^hello world$/iThe subject has to start and end with “hello world” case-insensitively.
['hello', /hello$/]The subject has to either start or end with “hello”.

Controlling

Speed Kit allows monitoring and controlling of its behavior. Therefore, you can use the SpeedKit global object exposed to window implementing the SpeedKitGlobal interface.

For example, you can bind code to the window's load event and read out several properties of SpeedKit:


              <!DOCTYPE html>
              <html>
                <head> <!-- ... --> </head>
                <body>
                  <!-- ... -->
            
                  <script>
                    window.addEventListener("load", function () {
                      // Monitor whether Speed Kit served the last page load:
                      var speedKitServedTheLastPageLoad = SpeedKit.lastNavigate.served;
                    });
                  </script>
                </body>
              </html>
            

Usage with Google Analytics

Use the global SpeedKit object to send Service Worker performance metrics to Google Analytics. When you add custom dimensions and metrics to your Google Analytics, you can keep track of how Speed Kit handled and improved your user's perceived performance.

Custom dimensions for Speed Kit in Google Analytics

In this example, we added three custom dimensions: Speed Kit was enabled, Speed Kit has served and Speed Kit had a cache hit with the scope set to “Hit” to our Google Analytics. After adding these custom dimensions, we can now send values for them using the ga function. This looks like the following:


              (function(i, s, o, g, r, a, m) {
                i['GoogleAnalyticsObject'] = r;
                i[r] = i[r] || function() {
                      (i[r].q = i[r].q || []).push(arguments)
                    }, i[r].l = 1 * new Date();
                a = s.createElement(o),
                    m = s.getElementsByTagName(o)[0];
                a.async = 1;
                a.src = g;
                m.parentNode.insertBefore(a, m)
              })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
            
              ga('create', 'UA-XXXXXXXX-Y', 'auto');
            
              // Set the custom dimensions' values
              ga('set', 'dimension1', SpeedKit.lastNavigate.enabled);
              ga('set', 'dimension2', SpeedKit.lastNavigate.served);
              ga('set', 'dimension3', SpeedKit.lastNavigate.cacheHit);
            
              ga('send', 'pageview');
            

You can use these dimensions to compare the performance with Speed Kit (`dimension2 === true`) to the performance without (`dimentsion2 === false).

Additional to the dimension, you can track custom metrics to capture more details. In the following example, we added 6 custom metrics to Google Analytics for the six performance metrics sent by Speed Kit. We then pass the loaded values to the ga function:


              // Send Speed Kit performance metrics to Google Analytics
              if (SpeedKit.lastNavigate.timings) {
                ga('set', 'metric1', SpeedKit.lastNavigate.timings.handleStart);
                ga('set', 'metric2', SpeedKit.lastNavigate.timings.handleEnd);
                ga('set', 'metric3', SpeedKit.lastNavigate.timings.cacheStart);
                ga('set', 'metric4', SpeedKit.lastNavigate.timings.cacheEnd);
                ga('set', 'metric5', SpeedKit.lastNavigate.timings.fetchStart);
                ga('set', 'metric6', SpeedKit.lastNavigate.timings.fetchEnd);
              }
            

SpeedKitGlobal

A global controller object containing client-side information and operations.

lastNavigate

Holds metadata of the user's last navigation.

readyState

Describes the loading state of the Speed Kit global object.

Type: 'loading' | 'complete'

subscribe

Subscribes to Web Push Notifications.

Type: () ⇒ Promise<WebPushState>

An object of metadata about the user's last navigate request.

The browser which performed the navigate request.

Type: string

The version of the browser which performed the navigate request.

Type: number

Indicates whether the navigate request was served from Speed Kit's Service Worker Cache.

Type: boolean

Indicates whether Speed Kit was enabled during the navigate request.

Type: boolean

Indicates whether Speed Kit has served the navigate request.

Type: boolean

Holds an object of Service Worker timings of the navigate request.

Type: undefined | ServiceWorkerTimings

ServiceWorkerTimings

An object containing millisecond timestamps for given events.

Combine these timings with e.g. the Performance API to track page load times in more detail.

cacheEnd

The timestamp in milliseconds when the cache lookup was finished.

Type: undefined | number

cacheStart

The timestamp in milliseconds when the cache lookup was started.

Type: undefined | number

fetchEnd

The timestamp in milliseconds when the Speed Kit network request returned.

Type: undefined | number

fetchStart

The timestamp in milliseconds when the Speed Kit network request started.

Type: undefined | number

handleEnd

The timestamp in milliseconds when Speed Kit was finished handling the request.

Type: undefined | number

handleStart

The timestamp in milliseconds when Speed Kit started handling the request.

Type: undefined | number