Speed Kit 1.16.2

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.16.2 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

Events

Use the following custom window events to react to Speed Kit's API.

speed-kit-completed (since 1.14.0)

Is fired once Speed Kit's statistics are initialized.

Use this event to read out Speed Kit's statistics and send them to your server. You can use this event for example to trigger an event in Google Analytics. See the following example:


              function sendMetrics() {
                var state = 0;
                var label = 'disabled';
            
                if (SpeedKit.lastNavigate.enabled) {
                  state = 1;
                  label = 'enabled';
                }
                if (SpeedKit.lastNavigate.served) {
                  state = 2;
                  label = 'served';
                }
                if (SpeedKit.lastNavigate.cacheHit) {
                  state = 3;
                  label = 'cacheHit';
                }
            
                // Send a custom Google Analytics Event "SpeedKit" with Speed Kit's metrics
                ga('send', 'event', 'SpeedKit', 'state', label, state, {
                  nonInteraction: true
                });
              }
            
              // Ensure Speed Kit is available
              if (SpeedKit) {
                // If Speed Kit is already complete, send metrics directly
                if (SpeedKit.readyState === 'complete') {
                  sendMetrics();
                } else {
                  window.addEventListener('speed-kit-completed', function () {
                    sendMetrics();
                  });
                }
              }
            

Please note: When using the API, please make sure that Speed Kit is available and is not already completed by using the SpeedKit.readyState property like in the example. Also, if you want to send page loading metrics, ensure that the load event was already fired. You can do this for example by using jQuery:


              $(function () {
                // Ensure Speed Kit is available
                if (SpeedKit) {
                  // If Speed Kit is already complete, send metrics directly
                  if (SpeedKit.readyState === 'complete') {
                    sendMetrics();
                  } else {
                    window.addEventListener('speed-kit-completed', function () {
                      sendMetrics();
                    });
                  }
                }
              });
            

speed-kit-loaded (since 1.1.0)

Is fired once Dynamic Blocks are replaced or replacement is found to be unnecessary on the page.

Use the active property of the event payload to check whether Dynamic Blocks were activated on the page.


              window.addEventListener('speed-kit-loaded', function (didChange) {
                console.log('Dynamic content was ' + (didChange ? 'replaced' : 'not found'));
              });
            

Payload: object { active: boolean }

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.

blocks (since 1.15.0)

Define blocks within your document which contain dynamic content.

Use this attribute to define areas within your HTML document which have dynamic content, i.e. content which should be fetched from your server instead of being bypassed and cached by Speed Kit. Use this approach to display heavily-changing or customer-specific information.

Each block is identified by a CSS Selector which defaults to ".speed-kit-dynamic". You can also specify an attribute to use as an identifier and a merge function that updates the HTML when content has been loaded from your server. To learn more, see the DynamicBlock section.

As an example for a shop system you could specify your blocks as in the following listing:


                var dynamicBlockConfig = {
                  blocks: [{
                    // Define a shopping cart area within your shop
                    selector: '.shopping-cart',
                    idAttribute: 'id',
                    merge: (oldEl, newEl) => oldEl.outerHTML = newEl.outerHTML
                  }, {
                    // Define a teaser area which displays products specific to the customer
                    selector: '.magic-teaser',
                    idFunction: (el) => $(el).data('dynamic-id'),
                    merge: (oldEl, newEl) => oldEl.outerHTML = newEl.outerHTML
                  }]
                };
                

Allowed values: DynamicBlock[] | DynamicBlock

Default value: [] (an empty array)

defaultSelector (since 1.15.0)

The default CSS Selector to identify dynamic blocks.

You can use any valid CSS Selector. The default is ".speed-kit-dynamic", i.e. every HTML element which has a speed-kit-dynamic class.

To define different selectors for different blocks, use the DynamicBlockConfig.blocks property (see also: DynamicBlock.selector).

Allowed values: string

Default value: ".speed-kit-dynamic"

defaultIdAttribute (since 1.15.0)

The default HTML tag attribute to get a unique block ID from.

With this property the Dynamic Fetcher receives the HTML attribute's name to get the unique block ID of a dynamic block's HTML element.

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 a data attribute or just element IDs for example.

If a dynamic block has no such attribute and you cannot add them, you can instead use a function to generate a unique ID from the dynamic block as an input value. See therefore the defaultIdFunction property.

Note: This property is overriden by the defaultIdFunction property.

To define different ID attributes for different blocks, use the DynamicBlockConfig.blocks property (see also: DynamicBlock.idAttribute).

Allowed values: string

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

Example value: "id"

Use the element's ID to obtain a unique ID for this dynamic block.

defaultIdFunction (since 1.15.0)

advanced The default function to get a unique ID from a dynamic block.

Each dynamic block needs a unique ID in order to be replaced with the right content. This function should return a unique ID which the Dynamic Fetcher can use. The function receives the HTML element as parameter and returns a string.

If no defaultIdFunction is given, Speed Kit will use the defaultIdAttribute.

Note: This property overrides the defaultIdAttribute property.

ParameterDescription
elementThe dynamic block to get the ID from.

To define a different ID function for a different block, use the DynamicBlockConfig.blocks property (see also: DynamicBlock.idFunction).

Allowed values: (element: HTMLElement) ⇒ string

Example value: (element) => element.tagName + '-' + element.children.length

Create the element's dynamic block ID by concatenating the element's tag name and its amount of children.

defaultMergeFunction (since 1.15.0)

advanced The default function to merge downloaded blocks of dynamic content into the DOM.

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

ParameterDescription
localBlockThe dynamic block from the current DOM (the cached version of the site).
remoteBlockThe corresponding dynamic loaded from the origin (personalized version of the site).

To define different merge functions for different blocks, use the DynamicBlockConfig.blocks property (see also: DynamicBlock.mergeFunction).

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

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

blockSelector (deprecated; introduced in 1.1.0)

The default HTML tag attribute to get a unique block ID from.

Deprecated: Renamed to defaultSelector in 1.15.0.

Allowed values: string

tagAttribute (deprecated; introduced in 1.1.0)

The default HTML tag attribute to get a unique block ID from.

Deprecated: This property has been split: Use either defaultIdAttribute (when using a string) or defaultIdFunction (when using a function).

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

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"

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

customMergeFunction (deprecated; introduced in 1.5.0)

advanced The default function to merge downloaded blocks of dynamic content into the DOM.

Deprecated: Renamed to defaultMergeFunction in 1.15.0.

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

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: HTTPRequest) ⇒ HTTPRequest

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

HTTPRequest (since 1.15.0)

This request object holds information to send in an HTTP request.

url (since 1.15.0)

required The URL to send the request to.

Allowed values: string

method (since 1.15.0)

The HTTP method to use, one of GET, POST, PUT, HEAD, etc.

Allowed values: string

Default value: "GET"

headers (since 1.15.0)

HTTP headers to send with the request.

Pass an object whose keys are the header names and its values are the header values.

Allowed values: { [ string ]: string }

Default value: {} (an empty object)

timeout (since 1.15.0)

The timeout in milliseconds after which the request should fail.

If no timeout is given or the timeout is zero, the timeout will not be set.

Allowed values: number

DynamicBlock (since 1.15.0)

A dynamic block defines an area of dynamic content within the HTML.

selector (since 1.15.0)

required The CSS Selector to identify this dynamic block.

You can use any valid CSS Selector. Please ensure to use a unique selector for each block.

Allowed values: string

idAttribute (since 1.15.0)

The HTML tag attribute to get a unique ID for this block from.

With this property the Dynamic Fetcher receives the HTML attribute's name to get the unique block ID of this dynamic block's HTML element.

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 a data attribute or just element IDs for example.

If a dynamic block has no such attribute and you cannot add them, you can use a function to generate a unique ID from the dynamic block as an input value. See therefore the idFunction property.

Note: This property is overriden by the idFunction property.

By default, the ID is taken from either DynamicBlockConfig.defaultIdFunction or DynamicBlockConfig.defaultIdAttribute.

Allowed values: string

idFunction (since 1.15.0)

advanced The function to get a unique ID from this dynamic block.

Each dynamic block needs a unique ID in order to be replaced with the right content. This function should return a unique ID which the Dynamic Fetcher can use. The function receives the HTML element as parameter and returns a string.

If no idFunction is given, Speed Kit will use the idAttribute.

Note: This property overrides the idAttribute property.

ParameterDescription
elementThe dynamic block to get the ID from.

By default, the ID is taken from either DynamicBlockConfig.defaultIdFunction or DynamicBlockConfig.defaultIdAttribute.

Allowed values: (element: HTMLElement) ⇒ string

mergeFunction (since 1.15.0)

advanced A function to merge this downloaded block of dynamic content into the DOM.

Defines a custom function to merge the dynamic content for this block loaded from the origin into its cached counterpart.

ParameterDescription
localBlockThe dynamic block from the current DOM (the cached version of the site).
remoteBlockThe corresponding dynamic loaded from the origin (personalized version of the site).

By default, the merge function is taken from DynamicBlockConfig.defaultMergeFunction.

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

SpeedKitConfig

Add the following properties to your speedKit variable.

appName

required The name of your Baqend app.

Allowed values: string

appDomain

advanced The domain to connect to your Baqend app.

Allowed values: string

Example value: speed-kit.example.org

disabled

Whether to disable the service worker on this page.

Allowed values: boolean

Default value: false

split

advanced Sets the probability that group A is chosen in the A/B test that enables Speed Kit for a percentage of users.

All users that are assigned to group "B" will not benefit from Speed Kit but serve as the control group to compare performance and business metrics against.

The value can vary from 0.0 to 1.0. If you specify null or any value larger then 1.0, all users whose browser supports Service Workers will have Speed Kit enabled.

Also compare the following table for some example values:

ValueDescription
0.00Speed Kit is always disabled.
0.5050% of users will get Speed Kit enabled while the other 50% will be disabled.
0.9595% of users will get Speed Kit enabled while 5% will be disabled to serve as the control group.
1.00Speed Kit is always enabled for users with supporting browsers.
nullSpeed Kit is always enabled (the default value).

Allowed values: number | null

Default value: null

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: [] (an empty array)

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

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: [] (an empty array)

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

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: [] (an empty array)

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

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: [] (an empty array)

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

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

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

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"

scope

advanced The Scope under which Speed Kit will be active.

Allowed values: string

Default value: "/"

maxStaleness (deprecated)

advanced The refresh interval of the Bloom filter in milliseconds.

Deprecated: Use SpeedKitConfig.refreshInterval (in seconds) instead.

Allowed values: number

Default value: 300000

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.

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.

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

disableCache

advanced Disables using the ServiceWorker cache.

Allowed values: boolean

Default value: false

preloadBloomFilter

advanced Load the Bloom filter when activating Speed Kit.

Allowed values: boolean

Default value: true

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

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.

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: [] (an empty array)

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

relativeModuleImports (since 1.13.0)

advanced Whether relative imports are used for JavaScript modules.

Allowed values: boolean

Default value: false

preloadDynamicBlocks (since 1.15.0)

advanced Preloads the personalized version of the page for dynamic blocks

If enabled, Speed Kit loads the personalized version of the page from the origin right after the navigate request instead of waiting for the Dynamic Fetcher to be executed.

Note: This should only be enabled when the Dynamic Fetcher is in use. With this option enabled, all navigate requests handled by Speed Kit also trigger a fetch of the origin's version of the resource.

Allowed values: boolean

Default value: false

sdnSetup (since 1.15.0)

advanced Whether Speed Kit runs in a Speed Kit Delivery Network (SDN) setup.

Note: This must be enabled when Speed Kit runs in the Speed Kit Delivery Network (SDN) setup.

Allowed values: boolean

Default value: false

sessionLifetime (since 1.16.0)

advanced Specifies the lifetime of the user's session which is used for performance tracking.

Allowed values: number

Default value: 1800

ResourceRule (since 1.11.0)

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 (since 1.5.0)

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.

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.

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.

ImageOptions (since 1.5.0)

These options can be applied on images.

See the image option for more information.

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

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

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

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

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

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

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

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.

SpeedKitRule

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

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\//

host

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

Allowed values: Condition

Example value: /\.com$/

pathname

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

Allowed values: Condition

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

mobile (since 1.5.0)

Only fulfills this rule if sent from a mobile device.

Allowed values: true

desktop (since 1.5.0)

Only fulfills this rule if sent from desktop.

Allowed values: true

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

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.

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.

ContentType

ValueDescription
DocumentApplies to HTML documents.
AudioApplies to audio files like MP3, WAV, or OGG.
VideoApplies to resources which are videos.
TrackApplies to resources which are subtitle tracks of the WebVTT format.
ImageApplies to resources which are images.
StyleApplies to resources which are style sheets.
ScriptApplies to resources which are JavaScript files.
FontApplies to resources which are fonts.

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>
            

A/B Testing

One use case for these variables is that you can perform A/B tests with your users. Take for example SpeedKit.lastNavigate.enabled as a split criterion for your test and find out which performance differences your users experience and how this changes the conversion. This allows you to keep an eye on how much Speed Kit increases user engagement and performance on your website.

To create a target group with a given probability, you can use the split property of the Speed Kit configuration. If you specify e.g. a value of 0.95, only 95 % all users will be part of Group A who will receive Speed Kit while all others are part of Group B who will not.

In the following example, the target group for our A/B test is determined by SpeedKit.lastNavigate.enabled and SpeedKit.lastNavigate.firstLoad. The latter is needed to exclude first-load visitors from the “inactive” tracking because they would bias the performance uplift measurements. This is due to the fact that Speed Kit's Service Worker cannot speed up the first navigate of a user. Furthermore, we set the control group to a size of 15% (so 85% will have Speed Kit enabled). We use jQuery to await the window to be loaded and report to Google Analytics:


            // Specify a config
            var speedKit = {
              appName: 'hello-world-123',
              split: 0.85 // 85 % of users will have Speed Kit enabled.
            };
            
            // Speed Kit Snippet
            !function(e,n,t,r,i,o){"use strict";/* ... */}
            
            /**
             * Determines the user's target group in an A/B test.
             */
            function getTargetGroup() {
              if (SpeedKit.lastNavigate.enabled) {
                return 'SPEED_KIT_ACTIVE';
              }
            
              // Speed Kit cannot serve the first load
              if (SpeedKit.lastNavigate.firstLoad) {
                return 'FIRST_LOAD';
              }
            
              return 'SPEED_KIT_INACTIVE';
            }
            
            // Evaluation using the group
            $(function() {
              var timing = performance.timing;
              ga('set', 'dimension1', getTargetGroup());
              ga('set', 'metric1', timing.loadEventEnd - timing.navigationStart);
            });
            

SpeedKitGlobal

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

subscribe

Subscribes to Web Push Notifications.

Calling this function will ask the user for permission and add a subscription for Web Push Notifications sent from the Speed Kit Service Worker.

Type: () ⇒ Promise<WebPushState>

lastNavigate

Holds metadata of the user's last navigation.

Use the lastNavigate object to retrieve timings and flags about the last navigate request by the user, helping you to analyze their perceived performance.

readyState

Describes the loading state of the Speed Kit global object.

Only once the state is 'complete', all the values of this object are final.

Type: "loading" | "complete"

sessionId

The unique ID of the user's session.

The ID is stored locally and kept intact for the same session. The ID may change when the user clears cookies and local storage.

Type: string

swSupported

Indicates whether Service Workers are supported in the browser.

Speed Kit can only accelerate the page if the browser supports Service Workers.

Type: boolean

userId

The unique ID of the user loading the page.

The ID is stored locally and kept intact for the same user. The ID may change when the user clears cookies and local storage.

Type: string

navigateId

ID of the current navigation

Type: string

track

Track custom events

Type: (action: string, label: string, value: number) ⇒ void

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

Indicates whether Speed Kit was enabled during the navigate request.

Type: boolean

Indicates whether Speed Kit has served the navigate request.

This also indicates that Speed Kit was enabled.

Type: boolean

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

Worker Cache.

When this is true, no request was needed to perform against your origin backend to render the page for the user and the HTML was loaded from the Service Worker Cache. It is still possible that a request was asynchronously performed against your server, e.g. to fetch the user's cookies.

This also indicates that Speed Kit was enabled and served the request.

Type: boolean

Indicates whether the navigate was the first load of the user.

Speed Kit gets enabled during the first load. This field lets you identify these navigates.

Type: boolean

The browser which performed the navigate request.

Type: string

The version of the browser which performed the navigate request.

Type: number

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

The Fastly cache hit indicates if the requested object was provided by their cache.

The following states are possible: HIT, MISS and SHIELD HIT

Type: string | null

The time duration of a Fastly cached asset.

Type: number | null

The point of presence as location of the Fastly cached asset.

Type: string | null

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.

handleStart

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

Type: number

handleEnd

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

Type: number

cacheStart

The timestamp in milliseconds when the cache lookup was started.

cacheEnd

The timestamp in milliseconds when the cache lookup was finished.

fetchStart

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

fetchEnd

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