Speed Kit 2.17.6
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 NotesDownload
Use the following links to download version 2.17.6 of Speed Kit.
- Service Worker
The Service Worker needs to be served from your website under the root directory, i.e.
Download sw.jshttps://www.example.org/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 this code to handle Dynamic Blocks. It needs to be included at the bottom of the cached version of your page when you use Dynamic Blocks, e.g. for personalized or segmented content.
Download dynamic-fetcher.js - Legacy Dynamic Fetcher
Use this code to handle Dynamic Blocks if it is executed not only on the cached version of your site:
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.
document.addEventListener('speed-kit-loaded', function (didChange) {
console.log('Dynamic content was ' + (didChange ? 'replaced' : 'not found'));
});
Payload: object { active: boolean }
dynamic-fetcher-data-ready
(since 2.3.1)
Is fired once all the data tracked from Speed Kit is set on the SpeedKit.dynamicBlocks object.
document.addEventListener('dynamic-fetcher-data-ready', function () {
sendMetrics();
});
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',
};
// ... 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. More information about Dynamic Blocks are written in the documentation.
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',
mergeFunction: (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'),
mergeFunction: (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"
"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.
Parameter | Description |
---|---|
element | The 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, index: number) ⇒ string
(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.
Parameter | Description |
---|---|
localBlock | The dynamic block from the current DOM (the cached version of the site). |
remoteBlock | The 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, prerenderedElements?: PrerenderedElement[]) ⇒ 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, index: number) ⇒ 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"
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, prerenderedElements?: PrerenderedElement[]) ⇒ void
requestTransformFunction
(deprecated)
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.
Deprecated: Use SpeedKitConfig.dynamicBlockUrlTransform instead.
Parameters:
request
- The origin request to get the personalized page.
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
delayDOMLoadedEvent
advanced Releases the DOMContentLoaded event in combination with usage of delay script.
To ensure the DOMContentLoaded event is fired after the execution of the Dynamic Fetcher. An empty JavaScript file named "speed-kit-dom-ready.js"
should be placed on your server and included at the bottom of your HTML's body afterwards.
<script src="/speed-kit-dom-ready.js"></script>
Speed Kit recognizes this specific script and delays it until the Dynamic Fetcher finished executing. Since it is part of the DOM the DOMContentLoaded event is fired after the script is loaded.
Option to release delay script to set execution time of Dynamic Fetcher. If true
, the Dynamic Fetcher will release the delay script and will replace the dynamic blocks on ready state interactive (which is before DOMContentLoaded). If false
, the Dynamic Fetcher will not release the delay script and replace the dynamic blocks on DOMContentLoaded. In case you have the delay script included, you need to make sure to release the delay script manually by sending a POST request to /speed-kit-dom-ready.js
.
Allowed values: boolean
Default value: false
displayErrorPage
(deprecated; introduced in 1.21.0)
advanced
This option will take effect if the Dynamic Fetcher response from the origin returns an unsuccessful status code (i.e. >= 400). If true
, the Dynamic Fetcher will exchange the current site with the content of the unsuccessful response or display an error banner. If false
, the unsuccessful response is ignored by the Dynamic Fetcher and no Dynamic Blocks are exchanged.
Deprecated: The desired behaviour can now be implemented by setting custom response handlers via DynamicBlockConfig.clientErrorHandler or DynamicBlockConfig.serverErrorHandler.
Allowed values: boolean
Default value: true
customErrorBanner
(since 2.2.0)
Customizes the error banner which will be displayed, if the dynamic fetcher cannot load the response from the origin. This can either be a custom message, which will be displayed in the standard error banner or a callback, in which a fully customized banner can be implemented.
customClientErrorClass
(since 2.11.0)
Customizes the class name that will be set to the html element when the page produces a client error.
Allowed values: string
Default value: speed-kit-client-error
customOfflineClass
(since 2.11.0)
Customizes the class name that will be set to the html element when the page is offline.
Allowed values: string
Default value: speed-kit-offline
customServerErrorClass
(since 2.11.0)
Customizes the class name that will be set to the html element when the remote server is offline.
Allowed values: string
Default value: speed-kit-server-error
responseValidityCheck
(since 1.21.0)
advanced The function takes care of checking the validity of a Dynamic Fetcher response.
In case of an invalid response the dynamic fetcher will retry the request for a set number of times, which can be defined via the DynamicBlockConfig.dynamicFetcherRetryLimit option.
Parameters:
localDocument
- The local document.
remoteDocument
- The remote document.
Allowed values: (localDocument: Document, remoteDocument: Document) ⇒ boolean
Default value: () => true
dynamicFetcherRetryLimit
(since 1.21.0)
advanced
Defines the number of times the Dynamic Fetcher will try the dynamic block request if the received response is invalid or an error is received.
Allowed values: number
Default value: 2
safeInlineScripts
(since 1.21.0)
advanced
A CSS Selector or a custom function to identify inline JavaScripts which are considered safe to stay inside the rewritten HTML file. During the script evaluation process these will not be executed again since they are already interpreted by the browser.
offlineHandler
(since 2.3.0)
advanced
Sets a custom offline handler in case the dynamic block response indicates the user is offline. The default case will display an error banner, which can also be customized via the DynamicBlockConfig.customErrorBanner option.
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
Default value: defaultOfflineHandler
redirectHandler
(since 2.3.0)
advanced
Sets a custom redirect handler in case the dynamic block response was redirected. The defaultRedirectHandler will execute a validity check, to ensure the response fits the current site and otherwise reloads the page from the origin server.
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
Default value: defaultRedirectHandler
corsRedirectHandler
(since 2.3.0)
advanced
Sets a custom CORS redirect handler in case the dynamic block response is a CORS redirect. The defaultCorsRedirectHandler will reload the page and deactivate SpeedKit.
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
Default value: defaultCorsRedirectHandler
clientErrorHandler
(since 2.3.0)
advanced
Sets a custom client error handler in case the dynamic block response indicates a client side error (status 4xx). The defaultClientErrorHandler will replace the current page with the content of the error response.
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
Default value: defaultClientErrorHandler
notFoundHandler
(since 2.7.0)
advanced
Revalidates the origin response when receiving a 404 or 410 status from origin.
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
Default value: defaultNotFoundHandler
serverErrorHandler
(since 2.3.0)
advanced
Sets a custom server error handler in case the dynamic block response indicates a server error (status 5xx). The defaultServerErrorHandler will replace the current page with the content of the error response and deactivate Speed Kit.
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
Default value: defaultServerErrorHandler
prepareOriginResponse
(since 2.6.0)
advanced
Sets a custom function to manipulate the remote document before the dynamic blocks are merged into the local document. By that it is possible to change the content of the dynamic blocks (e.g removing lazy loading). The custom function requires the remote document as parameter and returns the manipulated document.
appName
(since 2.6.0)
The name of your Baqend app.
Allowed values: string
appDomain
(since 2.6.0)
advanced
The domain to connect to your Baqend app.
Allowed values: string
speed-kit.example.org
requestTimeout
(since 2.9.0)
advanced
The time until an additional request will be started in milliseconds.
Allowed values: number
Default value: -1 which deactivates the logic.
disableTracking
(deprecated; introduced in 2.8.0)
Prevents dynamic fetcher from tracking information.
Deprecated: The desired behaviour can now be controlled via the DynamicBlockConfig.rumTracking option.
Allowed values: boolean
Default value: false
rumTracking
(since 2.10.4)
advanced Enables Speed Kit Real User Monitoring (RUM) from the Dynamic Fetcher.
Note: If activated, this option will store user and session IDs.
You can also use TrackingOptions to specify how RUM tracking should behave.
Allowed values: boolean | TrackingOptions
Default value: true
detectDeviceMismatch
(deprecated; introduced in 2.10.0)
advanced The function can be used to detect device mismatches.
In case a device mismatch was found, the function should return a string that describes the mismatch scenario in the from "actual-expected" (e.g. desktop-mobile). This is then tracked by the Dynamic Fetcher. If no mismatch was found, the function should return null.
Deprecated: The desired behaviour can now be implemented by using DynamicBlockConfig.detectDevice for declaring a custom detect-device function.
Parameters:
localDocument
- The local document.
remoteDocument
- The remote document.
Allowed values: (localDocument: Document, remoteDocument: Document) ⇒ string | null
Default value: () => null
detectDevice
(since 2.11.0)
advanced
The function can be used to detect the device in the given document. If this function is specified, the device-mismatch-detection is automatically activated.
In case a device was found, the function should return the device as a string. This device is then used for detecting a device-mismatch with the origin (e.g. expected is "desktop" and actual is "mobile"). If a mismatch was found, the dynamic fetcher updates the custom device in the service-worker and tracks the mismatch by sending a beacon.
Parameters:
doc
- The document to search the device in.
Allowed values: (doc: Document) ⇒ string | null
Default value: () => null
changeDetectionSampling
(since 2.11.0)
Sampling rate for the change detection of hot resources.
Allowed values: number
Default value: 1 - Which always executes change detection.
0.1 - Executes change detection in 10% of the cases if the resource is hot.
prerendered
(since 2.12.0)
advanced
Specifies RenderedBlocks for sections we should not exchange during our merge.
Allowed values: RenderedBlock[]
assetChangeDetection
(since 2.12.0)
Enables change detection on assets (scripts & styles). If a change was detected e.g. because a script was missing in the cached version, a refresh job is triggered for that particular page. This can also be fine-tuned (e.g. excluding certain URLs) by using a AssetChangeDetectionConfig.
Allowed values: boolean | AssetChangeDetectionConfig
Default value: true
dynamicScriptExecution
(since 2.13.0)
Enables dynamic handling of differences in scripts between cached version and origin. Initially this will include executing external scripts that are only present in the origin document.
Allowed values: boolean
Default value: false
externalAssetList
required
List of detected external assets.
Allowed values: { , }
deferredScriptsInQueue
(since 2.13.0)
advanced Whether we already handle deferred scripts in our script queue in the deployed Document Handler.
Note: This is automatically set by the capable DocumentHandler version, manual use is not recommended.
Allowed values: boolean
enableCookieBotHandling
(since 2.15.0)
Enables special handling for Cookiebot Enables special handling for Cookiebot.
Allowed values: boolean
Default value: false
AssetChangeDetectionConfig
ignore
Allowed values: (string | RegExp)[]
reportOnly
Allowed values: boolean | "script"
| "style"
RenderedBlock
For cases where DynamicBlock elements are rendered dynamically in the page before the dynamic fetcher is executed.
selector
required
Allowed values: string
appendTo
Allowed values: string
insertBefore
Allowed values: string
replaces
Allowed values: string
removeIfMissing
Allowed values: boolean
ResponseHandlerContext
Context with gives the DynamicResponseHandlers access to critical information.
deactivateSpeedKit
required
Locally deactivates Speed Kit.
Allowed values: (disconnectCause?: DisconnectCause) ⇒ void
dynamicBlockResponse
required
The Dynamic Block response.
Allowed values: Document
ensureScriptValidity
required
Checks whether the scripts in documents are compatible and reloads the site otherwise.
Allowed values: Function
showOfflineBanner
required
Displays the offline banner set in the config.
Allowed values: () ⇒ void
domDelayActive
required
Whether DOM delay is activated.
Allowed values: boolean
canDisplayErrorPage
required
Toggles the error page, set in config.
Allowed values: boolean
trackChanges
required
Tracks changes in a DynamicBlockElement.
exchangeDocument
required
Exchange the current document with the remote response to show error site.
reloadFromOrigin
required
Reloads the current page from origin.
Allowed values: () ⇒ void
xhr
required
The state of the XMLHttpRequest.
Allowed values: XMLHttpRequest
defaultClientErrorHandler
required
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
defaultNotFoundHandler
required
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
defaultServerErrorHandler
required
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
defaultOfflineHandler
required
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
defaultRedirectHandler
required
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
defaultCorsRedirectHandler
required
Allowed values: (context: ResponseHandlerContext) ⇒ void | boolean
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.
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.
Parameter | Description |
---|---|
element | The dynamic block to get the ID from. |
By default, the ID is taken from either DynamicBlockConfig.defaultIdFunction or DynamicBlockConfig.defaultIdAttribute.
Allowed values: (element: HTMLElement, index: number) ⇒ string
mergeFunction
(deprecated; introduced in 1.15.0)
advanced
A function to merge this downloaded block of dynamic content into the DOM.
Deprecated: use merge instead
Allowed values: (localBlock: HTMLElement, remoteBlock: HTMLElement, prerenderedElements?: PrerenderedElement[]) ⇒ void
merge
(since 2.5.0)
advanced A function to merge this downloaded block of dynamic content into the DOM.
Either defines a custom function to merge the dynamic content for this block loaded from the origin into its cached counterpart or ist set to false
which means the defined block will not be merged.
Parameter | Description |
---|---|
localBlock | The dynamic block from the current DOM (the cached version of the site). |
remoteBlock | The corresponding dynamic loaded from the origin (personalized version of the site). |
By default, the merge function is taken from DynamicBlockConfig.defaultMergeFunction.
Allowed values: false | (localBlock: HTMLElement, remoteBlock: HTMLElement, prerenderedElements?: PrerenderedElement[]) ⇒ void
detectChanges
(since 2.5.0)
advanced
Provides the possibility to define a list of ChangeDetection, to inspect the cached version and the origin version of the current block for differences. In case the option is set to true
a default change detection will be executed, which consists of inspecting all image tags within the block and comparing their src
attribute and inspecting all anchor tags within the block and comparing their href
attribute.
Allowed values: boolean | ChangeDetection[]
removeIfMissing
(since 2.9.0)
Whether to remove a dynamic block that is only present in the cached version of the site.
A common example for this is a cookie banner that is always present in the anonymous cached version, but is missing in the origin version once the user has accepted the cookie terms.
Allowed values: boolean
Default value: false
insertBefore
(since 2.10.0)
advanced
Specifies a CSS selector that is used to find an element of the local document before which the dynamic block should be inserted that exists only in the remote document.
The dynamic block will be inserted right before the element found by the selector.
Allowed values: string
appendTo
(since 2.10.0)
advanced
Specifies a CSS selector that is used to find an element of the local document to which to append the dynamic block that exists only in the remote document.
Allowed values: string
isMainBlock
(since 2.13.0)
Specifies if the dynamic block is the main block or not.
Allowed values: boolean
Default value: false
ChangeDetection
Custom change detection to specify how dynamic blocks should be checked for differences.
find
(since 2.5.0)
advanced
The CSS Selector to identify this elements which should be compared for the change detection. In case no selector is specified the whole dynamic block will be considered as the element to compare.
Allowed values: string
compare
(since 2.5.0)
advanced
A list of properties which should be compared for the elements identified through the ChangeDetection.find option. Alternatively a CustomCompareFunction can be provided to compare the elements.
Allowed values: string[] | (local: HTMLElement, remote: HTMLElement) ⇒ string | null
ignoreQueryParams
(since 2.10.0)
advanced
Specifies a list of query parameters to be ignored when comparing the property of the identified elements. Set to true
if all parameters should be ignored.
limit
(since 2.13.0)
advanced
Limits the number of elements to be compared from the identified elements.
Allowed values: number
PrerenderedElement
localElement
required
Allowed values: Element | null
remoteElement
required
Allowed values: Element | null
mode
Allowed values: "insertBefore"
| "appendTo"
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
speed-kit.example.org
enabled
(since 2.7.0)
Whether to enable Speed Kit for the current user.
Allowed values: boolean
Default value: true
disabled
Whether to disable Speed Kit for the current user. This overrides the enabled flag.
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:
Value | Description |
---|---|
0.00 | Speed Kit is always disabled. |
0.50 | 50% of users will get Speed Kit enabled while the other 50% will be disabled. |
0.95 | 95% of users will get Speed Kit enabled while 5% will be disabled to serve as the control group. |
1.00 | Speed Kit is always enabled for users with supporting browsers. |
null | Speed Kit is always enabled (the default value). |
splitTestId
advanced ID to identify the active split test.
Should be used in combination with split
to identify the active split test. Change the split test id to start a new split test (e.g. when changing the split or configuration).
Allowed values: string
group
advanced Assigned split group.
This can be used to force a specific group. Otherwise this will be determined automatically on client side.
Allowed values: string
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)
[{ 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)
[{ 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)
[{ url: /robots\.txt$/, contentType: ["document"] }]
preloadBlacklist
Some rules for preload requests which should not be intercepted.
Using an empty rule array means that Speed Kit is preload blacklisted for no resource (this is the default).
Allowed values: SpeedKitRule[]
Default value: []
(an empty array)
[{ url: /robots\.txt$/, contentType: ["document"] }]
fetchlist
advanced
Some rules for requests which should always be fetched from origin by the Service Worker.
Allowed values: SpeedKitRule[]
Default value: []
(an empty array)
[{ url: /robots\.txt$/, contentType: ["document"] }]
delayed
(since 1.17.0)
Some rules for requests which should be intercepted but delayed.
You can use an array of DelayRules to tell Speed Kit how resources should be delayed. The config looks for example like this:
var speedKit = {
// ... other options ...
delayed: [
{
// Delay Google Tag Manager until one second after the load event
rules: [{ url: 'www.googletagmanager.com/gtm.js' }],
options: {
event: 'load',
timeout: 1000,
},
}, {
// apply options to resources under '/script/dynamic/'
rules: [{ pathname: '/script/dynamic/' }],
options: {
event: 'speed-kit-dynamic-loaded',
timeout: 0,
},
}
],
// ... other options ...
};
Delayed resources improve the critical rendering path of your website. All resources which are not matched by a rule will not be delayed by Speed Kit (this is the default).
You can also just pass an array of SpeedKitRules to this option if you do not want to specify the event up to which a resource is delayed (the "load" event is the default.):
var speedKit = {
// ... other options ...
delayed: {
[{ url: 'www.googletagmanager.com/gtm.js' }]
},
// ... other options ...
};
Allowed values: SpeedKitRule[] | DelayRule[]
Default value: []
(an empty array)
[{ rules: [{ pathname: '/script/dynamic/' }], { event: 'speed-kit-dynamic-loaded', timeout: 2000 } }]
In this example, Speed Kit will delay all resources under the '/script/dynamic/' path after the 'speed-kit-dynamic-loaded' event was fired plus a two second timeout. All other resources will not be delayed at all.
defer
(since 2.4.0)
Defers the specified requests until the Dynamic Blocks are applied.
For this option to work the cached HTML needs to include a script tag /speed-kit-dom-ready.js
as first script. Also, the delayDOMLoadedEvent
option in the Dynamic Block config must be enabled.
Allowed values: SpeedKitRule[]
Default value: []
(an empty array)
[{ pathname: '/script/dynamic/' }]
In this example, Speed Kit will not deliver the response for the request matching /script/dynamic/
until the Dynamic Fetcher has released the speed-kit-dom-ready.js file.
userAgentDetection
Enables user agent detection to handle mobile and desktop differently.
If user agent detection is enabled, Speed Kit distinguishes all 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.
You can also pass an array of SpeedKitRules to specify which resources should be distinguished.
Allowed values: SpeedKitRule[] | boolean
Default value: false
[{ contentType: ["document"]}]
This example shows the most common use case where Speed Kit will distinguish only the HTML requests. I.e. Speed Kit will serve different HTML files for desktop and mobile (if the origin provides them) but the same JS, CSS and image files.
stripQueryParams
(since 1.17.0)
Applies query parameter stripping to resources served by Speed Kit. Query params are only removed on network level. They can still be read and used in frontend code.
You can use an array of StripParamsRule to tell Speed Kit which query parameters should be stripped. The config looks for example like this:
var speedKit = {
// ... other options ...
stripQueryParams: [
{
// strip 'slow' param of resources under '/speed/' on enabled sites
enabledSites: [{ pathname: '/baqend/' }],
rules: [{ 'pathname': '/speed/' }],
params: ['slow'],
}, {
// strip 'country' query parameter of resources under '/product/prices/'
rules: [{ 'pathname': '/product/prices/' }],
params: ['country'],
}, {
// strip specified params for all resources
params: ['analytics', 'gclid'],
},
],
// ... other options ...
};
Alternatively, you can use a set of rules to match against query parameters to be stripped from all requested URLs. Every before they are fetched:
var speedKit = {
// ... other options ...
stripQueryParams: ['analytics', 'gclid'],
// ... other options ...
};
Allowed values: Condition | StripParamsRule[]
Default value: []
(an empty array)
[{ enabledSites: [{ 'pathname': '/products/' }], params: ['size', 'color'] }]
Speed Kit will remove “size” and “color” query parameters for all resources requested by enabled sites under '/products/'. For all other sites, the query parameters won't be removed.
customVariation
(since 1.21.0)
advanced
Applies a set of custom variation rules to Speed Kit requests. Unlike user agent detection this option can be configured with a custom function to determine the variation on a basis of currently set cookies and device type. Additionally, each rule can be configured regarding the sites on which it should be enabled and other conditions which have to be matched by the request. If two or more variation rules apply to a request, the rule defined last determines the variation.
Note: The provided function will only transmit an identifier for a custom variation to the server. In the server side runtime configuration a strategy for handling this variation (e.g. requesting assets with certain cookies) has to be defined.
Allowed values: VariationRule[]
Default value: []
(an empty array)
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
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
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
(deprecated)
advanced
Disables using the ServiceWorker cache.
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:
Value | Description |
---|---|
–1 | Do not tee the request (costs least bandwidth of your origin) – default. |
0 | Always tee the request (costs most bandwidth of your origin). |
X > 0 | Tee the request at most every X seconds (saves bandwidth of your origin). |
Allowed values: number
Default value: -1
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: {
optimize: 'high',
downscale: true,
},
}, {
// apply options to images under "/images/photos/"
rules: [{ "pathname": "/images/photos/" }],
options: {
optimize: 'medium',
webp: false,
},
}, {
// default options
options: {
optimize: 'medium',
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: {
optimize: 'high' ,// change default optimization from medium to high
webp: false, // disable WebP support which is enabled by default
},
// ... other options ...
};
Allowed values: ImageOptions | ImageRule[] | false
[{ rules: [{ "pathname": "/assets/img/" }], options: { optimize: 'medium', downscale: true } }]
In this example, Speed Kit will compress all images under the "/assets/img/" path with medium optimization and limit its size to the user's screen. All other images will not be manipulated at all.
You can disable the feature completely by setting the option to false
.
criticalResources
(deprecated; introduced in 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 ...
};
Deprecated:
Allowed values: (string | ResourceRule)[]
Default value: []
(an empty array)
[{ 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: true
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: SpeedKitRule[] | boolean
Default value: false
sessionLifetime
(deprecated; introduced in 1.16.0)
advanced
Specifies the lifetime of the user's session which is used for performance tracking.
Deprecated: Value is set to constant 1800 (30 minutes) since 2.10.4
Allowed values: number
Default value: 1800
rumTracking
(since 1.20.0)
advanced Enables Speed Kit Real User Monitoring (RUM).
Note: If activated, this option will make use of cookies to store user and session IDs.
You can also use TrackingOptions to specify how RUM tracking should behave.
Allowed values: boolean | TrackingOptions
Default value: false
sampleRate
(since 2.8.0)
advanced
Specifies the percentage of session that will send RUM data. Ranges from 0 to 1. RUM needs to be enabled for the sample rate to take effect.
Allowed values: number
Default value: 1
cookieLifetime
(since 2.4.0)
advanced
Specifies the lifetime of RUM Tracking Cookies in days.
Allowed values: number
Default value: 180
ignoreAfterPostNavigate
(since 1.20.0)
advanced
Whether Speed Kit blacklists first navigation after a Post Navigate.
Allowed values: boolean
Default value: true
customDevice
(deprecated; introduced in 2.2.0)
advanced
Set the device type inferred for the current user. If the device type is not set SpeedKit will determine it using the user agent and/or given custom variations.
Deprecated: Use SpeedKitConfig.detectDevice instead.
Allowed values: string | null | () ⇒ string | null | Promise<string | null>
disabledSites
(since 2.2.0)
Rules to identify html sites on which Speed Kit should not be enabled.
Using an empty rule array means that Speed Kit is enabled on sites specified by enabledSites option.
Allowed values: SpeedKitRule[]
Default value: []
(an empty array)
[{ url: /^www\.baqend\.com\/speedkit\//}]
precache
(since 2.4.0)
advanced A list of resources to be precached during Service Worker install event.
You can use an array of strings to tell Speed Kit which resources should be precached during the install event of the Service Worker. By that, the specified resources can be served by the bytecode cache of the browser (hot run) right after the Service Worker is installed.
Allowed values: (string | PrecacheRule)[]
Default value: []
(an empty array)
immutableAssets
(since 2.4.0)
Rules to identify assets that are immutable and therefore can always be taken from cache.
For security reasons, navigate requests can not be marked as immutable.
Allowed values: SpeedKitRule[]
Default value: []
(an empty array)
[{ url: /^www\.baqend\.com\/speedkit\/immutable\.js/}]
trackingRequests
(since 2.5.0)
Rules to identify tracking requests which send data to the origin. Those requests are answered with a 204 status code and the data is send to the origin by the Service Worker in the background.
Allowed values: SpeedKitRule[]
Default value: []
(an empty array)
[{ url: "www.baqend.com/speedkit/sendTracking.js" }]
sdnSetup
(since 2.6.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
offlinePage
(since 2.6.0)
Specifies a page that is always served when the client has no connection to the network.
Allowed values: string
"www.baqend.com/offline.html"
useCacheWhenOffline
(since 2.11.0)
Whether to respond to offline Requests with the SW cache.
Allowed values: boolean
executeInIframe
(since 2.6.0)
Whether the snippet shall be executed in an iFrame.
Depending on the configuration this includes tracking, setting of detected devices among others.
Allowed values: boolean
Default value: false
enableForWebViews
(since 2.6.1)
Allows Speed Kit to be enabled within WebViews.
Allowed values: boolean
Default value: false
includeServiceWorker
(since 2.8.0)
Includes a 2nd-party service worker.
Allowed values: string
enableOriginCache
(since 2.10.0)
Enables using the ServiceWorker cache for origin responses.
Allowed values: boolean
Default value: false
dynamicBlockUrlTransform
(since 2.15.0)
advanced A function to transform the dynamic block request url sent to origin.
Defines a custom function that transforms the url of the origin request used to fetch the personalized page which is used to switch out the Dynamic Blocks.
Allowed values: (request: Request, device: string | null, cookies: Map<string, string>) ⇒ string | string
resetResponseUrl
(since 2.11.0)
Resets the response URL from the Speed Kit domain to the original URL.
Allowed values: SpeedKitRule[]
omitImageCredentials
(since 2.11.0)
Sets the credentials header to 'omit' for image requests.
Allowed values: boolean
blockedRequests
(since 2.13.0)
Rules to identify requests which should be blocked by the Service Worker and answered with a status "blocked:SpeedKit".
Allowed values: SpeedKitRule[]
Default value: []
(an empty array)
[{ url: "www.baqend.com/speedkit/mustBeBlocked.js" }]
urlTransform
(since 2.12.0)
advanced
Applies a set of custom rules which modify Speed Kit requests URLs.
Allowed values: TransformRule[]
Default value: []
(an empty array)
detectDevice
(since 2.13.0)
advanced
Specifies the device of the current navigation.
Allowed values: string | null | (doc: Document) ⇒ string | null | Promise<string | null>
Default value: []
(an empty array)
shouldDetectDevice
(since 2.13.0)
advanced
A custom set of rules which specify if device should be appended to the request via a query string.
Allowed values: SpeedKitRule[]
Default value: [{ contentType: ['document'] }]
disableParamSorting
Ruleset to allow disabling of query parameter sorting.
We usually sort query parameters to avoid multiple cache entries because we use the URL as our cache key. In most cases this works, but sometimes the server response differs depending on the order of parameters. This option allows disabling the automatic sorting to ensure we always cache the correct content. By default, Parameter Sorting is disabled for all *.html requests.
Using an empty rule array means that the sorting is on for all requests.
Allowed values: SpeedKitRule[]
Default value: [{ contentType: [ContentType.Navigate] }, { pathname: /\.html/ }]
ruleSetConfig
The configuration for parsing the ruleset. no prefix match on query params & no query parameter evaluation on pathname rule Version 2 will
- not evaluate query parameters on pathname rule
- not match prefixes on query parameters
Allowed values: { }
apiChangeDetection
(since 2.17.0)
The configuration for the API Change Detection.
Allowed values: ApiChangeDetectionConfig | boolean
fetchInUnload
(since 2.17.0)
If this value is true, client will let service worker know when the page start unloading, and will fetch resources that is not in whitelist, blacklist, or fetchlist in the unload phase. If this value is false, client will not let service worker know and will also fetch resources that is not in whitelist, blacklist, or fetchlist both in and outside the unload phase.
Allowed values: boolean
Default value: true
enabledAPIs
(since 2.17.0)
Rules to identify api requests that should bypass enabledSites/disabledSites checks.
Using an empty rule array means that no requests will bypass the checks.
Allowed values: SpeedKitRule[]
Default value: []
(an empty array)
[{ pathname: '/api/' }]
watchStorageKeys
(since 2.17.0)
Specifies storage keys in `localStorage` and `sessionStorage` to watch for changes.
Speed Kit will monitor changes to these keys and synchronize them with the Service Worker.
Allowed values: (string | RegExp)[]
Default value: []
(an empty array)
['authToken', /^userPreference_/]
ApiChangeDetectionConfig
The configuration for the API Change Detection. Setting the config to true
will use default values.
whitelist
Specifies the range of asset URLs that are viable for the API CD. Defaults to [{ host: location.host }]
.
Allowed values: SpeedKitRule[]
blacklist
Excludes URLs from the API CD. Defaults to []
.
Allowed values: SpeedKitRule[]
onChange
Gets called every time we detect an API change.
compare
Can set a custom function to compare the cached with the remote API response.
Parameters:
local
- The cached API response.
remote
- The origin API response.
Allowed values: (local: string, remote: string) ⇒ { , , , } | { , , , }[]
sampleRate
Will set a percentage in which the API CD will execute. Defaults to 1
.
Allowed values: number
timeout
How long to wait in milliseconds until starting the API CD after detecting a matching request. Defaults to 1000ms.
Allowed values: number
TransformRule (since 1.23.0)
This rule transform the URL for the matching requests. See the custom variation option for more information.
rules
(since 1.23.0)
The rules to match resources against.
Allowed values: SpeedKitRule[]
transformFunction
(since 1.23.0)
required
The function to determine the URL for the requested resource.
Allowed values: (request: Request, device: string | null, cookies: Map<string, string>) ⇒ string | string
PrecacheRule
href
required
Allowed values: string
as
required
Allowed values: ContentType
TrackingOptions
performanceOnly
(since 2.5.1)
Prevents Speed Kit from storing user and session IDs.
Allowed values: boolean
Default value: false
stripAllParameter
(since 2.5.1)
Strips all parameter of URLs when sending data via RUM tracking. Afterwards the URL looks like this: https://www.baqend.com/page?redacted
.
Allowed values: boolean
Default value: false
stripParameters
(since 2.7.0)
Strips individual parameter of URLs when sending data via RUM tracking. Afterwards the URL looks like this: https://www.baqend.com/page?redacted-0¬filtered=foo
.
Allowed values: string[]
noCookies
(since 2.5.1)
When activated, Speed Kit does not use cookies to store data.
Allowed values: boolean
Default value: false
noTracking
(since 2.5.1)
When activated, Speed Kit does not send any tracking data.
Allowed values: boolean
Default value: false
dataLayer
Option to specify a custom data layer property if the customer does not use 'dataLayer'.
Allowed values: string
VariationRule (since 1.21.0)
A cookie variation rule determines the needed variation for the current request. See the custom variation option for more information.
rules
(since 1.21.0)
The rules to match only some resources.
Allowed values: SpeedKitRule[]
[{ url: 'www.googletagmanager.com/gtm.js' }]
In this example, Speed Kit will apply the rule to determine the variation only for the Google Tag Manager request. All other resources will not be affected by this rule.
variationFunction
(since 1.21.0)
required
The function to determine the variation for the requested resource. The function can also be declared as string representation. Parameters for the variation function are the current request, the device type and the cookies which are currently set. The output is an variation identifier for which a custom handling has to be implemented in the server runtime configuration.
Allowed values: (request: Request, device: string | null, cookies: Map<string, string>, storage: { [key: string] => string }) ⇒ string | string
StripParamsRule (since 1.17.0)
A strip query params rule selects a subset of resources and strips some params of it. See the strip query params option for more information.
enabledSites
(since 1.17.0)
The sites on which this strip query params rule is enabled.
Allowed values: SpeedKitRule[]
[{ "pathname": "/product/details/" }]
In this example, Speed Kit will strip query params given by the params
property from all resources requested from a product details page under the path of "/product/details/". All other resources will not be affected by this rule.
rules
(since 1.17.0)
The rules to match only some resources.
Allowed values: SpeedKitRule[]
[{ url: 'www.googletagmanager.com/gtm.js' }]
In this example, Speed Kit will strip query params given by the params
property of the Google Tag Manager request. All other resources will not be affected by this rule.
params
(since 1.17.0)
required
The params to be stripped from the selected resources.
Allowed values: Condition
['analytics', 'gclid']
Speed Kit will remove “analytics” and “gclid” query parameters before issuing and caching the request.
DelayRule (since 1.17.0)
A delay rule selects a subset of resources and applies some DelayOptions to it. See the delayed option for more information.
rules
(since 1.17.0)
required
The rules to match only some resources.
Allowed values: SpeedKitRule[]
[{ url: 'www.googletagmanager.com/gtm.js' }]
Speed Kit will delay the Google Tag Manager request to speed up all render-critical requests.
options
(since 1.17.0)
The options to apply to the selected resources.
Allowed values: DelayOptions
{ event: 'load', timeout: 1000 }
Delays all resources affected by this rule until the load event has been completed plus a one second timeout.
DelayOptions (since 1.17.0)
These options can be applied on resources. See the delayed option for more information.
event
(since 1.17.0)
The DelayEvent up to which a resource is delayed.
Allowed values: DelayEvent
Default value: "load"
timeout
(since 1.17.0)
The time in milliseconds that must be waited after the event has been completed.
Allowed values: number
Default value: 1000
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[]
[{ 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[]
["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[]
[{ "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[]
[{ "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)
The options to apply to the selected images.
Allowed values: ImageOptions
{ quality: 75, webp: false }
Applies a quality of 75% and disables WebP support for all images affected by this rule.
imageFunction
(since 2.11.0)
advanced
Callback that adapts image URL.
Allowed values: (request: Request, clientURL: string, cookies: Map<string, string>, params?: ImageOptions, screenSize?: number) ⇒ ImageOptions | string
ImageOptions (since 1.5.0)
These options can be applied on images. See the image option for more information.
quality
(deprecated; introduced in 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
.
optimize
(since 2.4.0)
Automatically applies optimal quality compression to produce an output image with as much visual fidelity as possible, while minimizing the file size.
The following values are allowed:
Value | Description |
---|---|
low | Output image quality will be similar to the input image quality. |
medium | More optimization is allowed. Preserve the visual quality of the input image. – default. |
high | Minor visual artefacts may be visible. This produces the smallest file. |
You can disable the feature completely by setting the option to false
.
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.
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.
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
[20, 10, 200, 400]
Crops a 200 × 400 pixel area from 20 pixels on the X axis and 10 pixels on the Y axis.
overrideWidth
(since 1.17.0)
advanced Defines a query parameter which is used as the width setting for Speed Kit's image optimization.
If your website requests tailored images based on a query parameter describing the width of that image, you should set this option to the parameter, so Speed Kit can use it for optimization. With this setting, images are delivered in the right size and cache hit rate can be greatly improved.
E.g., you have an image delivered under https://www.example.org/my-image.png
. Now, you link the image using https://www.example.org/my-image.png?width=512
to have it scaled down to a width of 512 pixels. Then, you can specify "width"
for overrideWidth
.
false
will disable this functionality (default).
overrideHeight
(since 1.17.0)
advanced Defines a query parameter which is used as the height setting for Speed Kit's image optimization.
If your website requests tailored images based on a query parameter describing the height of that image, you should set this option to the parameter, so Speed Kit can use it for optimization. With this setting, images are delivered in the right size and cache hit rate can be greatly improved.
E.g., you have an image delivered under https://www.example.org/my-image.png
. Now, you link the image using https://www.example.org/my-image.png?height=512
to have it scaled down to a height of 512 pixels. Then, you can specify "height"
for overrideHeight
.
false
will disable this functionality (default).
format
(since 2.11.0)
advanced Specifies the desired output encoding which would be used for the image optimization.
The format parameter enables the source image to be converted from one encoded format to another. This is useful when the source image has been saved in a sub-optimal file format that hinders performance.
E.g., you have an image that wants to be converted to PNG8 for example, therefore, the request format param will look like ?format=png8
or ?format=jpg&quality=95 for progressive JPEG with 95% quality.
avif
(since 2.15.0)
Converts images to the avif format.
If your user's browser supports the avif format, your images are automatically converted to this format.
Allowed values: boolean
Default value: false
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
/^www\.baqend\.com\//
host
A condition to test against the host, e.g. “www.baqend.com”, “www.baqend.com:8443”.
Allowed values: Condition
/\.com$/
pathname
A condition to test against the path name, e.g. “/some/path/here”.
Allowed values: Condition
/\/robots\.txt$/
hashparam
A condition to test against the hash parameters, e.g. “campaign”.
Allowed values: Condition
/campaign/
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
cookie
(since 1.17.0 - prior versions only match cookie names)
A condition tested against cookies.
Use the cookie rule to test if a cookie with a given name and/or value. The Condition that you pass to this attribute will be matched against all available cookies (in the form of name=value
) and this rule is fulfilled, when there exists at least one cookie that matches that Condition.
Allowed values: Condition
/^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[]
["document", "style", "script", "image"]
Only apply this rule to HTML documents, CSS files, JavaScript files and images.
ruleSetVersion
The RuleSet version number. This will affect the parsing of the RuleSet.
Allowed values: number
ContentType
Value | Description |
---|---|
document | Applies to HTML documents. |
navigate | Applies to navigate requests on a document. |
fetch | Applies to fetch and XHR requests on a document. |
audio | Applies to audio files like MP3, WAV, or OGG. |
video | Applies to resources which are videos. |
track | Applies to resources which are subtitle tracks of the WebVTT format. |
pdf | Applies to resources which are PDF files. |
image | Applies to resources which are images. |
style | Applies to resources which are style sheets. |
script | Applies to resources which are JavaScript files. |
font | Applies to resources which are fonts. |
undefined | Applies to everything else. |
DelayEvent
Value | Description |
---|---|
load | Delays after load event. |
speed-kit-dynamic-loaded | Delays after the Dynamic Fetcher has completed for all dynamic blocks. |
DisconnectCause
Value | Description |
---|---|
SWException | |
BloomfilterException | |
DashboardDisabled | |
ServerError | |
PostMessage | |
CORSRedirect | |
Offline | |
OriginServerError | |
None | |
AssetTimeout |
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$/i | The 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 a Partial of 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.
Type: NavigateMetadata
readyState
Describes the loading state of the Speed Kit global object.
syncPrepared
: synchronous execution of this object's initialization is completed. complete
: both synchronous and asynchronous executions of this object's initialization are completed. For example, SpeedKit.lastNavigate.applicationState value only exists after asynchronous execution.
Type: ReadyState
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
group
Represents the chosen group for the A/B Test.
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.
Type: string
actualGroup
Represents the chosen group for the A/B Test information from last navigate.
Type: string
split
(since 1.21.0)
Represents the chosen split for the A/B Test on a scale from 0 to 1.
In case of 1
100% of the users would be assigned to group A and none to B. In case of 0.5
50% of the users would be assigned to group A and 50% to group B.
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
sessionIndex
(since 1.21.0)
Index of this page impression in the current session.
Type: number
controllingServiceWorker
(since 1.20.0)
The Service Worker url that was controlling the navigation.
track
Track custom events
Parameters:
action
- The action which triggered the custom event.
label
- The label of the custom event.
value
- The value of the custom event.
immediately
- Indicates whether the event should be sent directly or collapsed with other events.
withTimestamp
- Indicates whether the event should include a timestamp.
Type: (action: string, label: string, value: number, immediately?: boolean, withTimestamp?: boolean) ⇒ void
splitTestId
The ID of the user's assigned split test.
Type: string
actualSplitTestId
The ID of the user's assigned split test from last navigate.
Type: string
rumController
(since 1.19.0)
The controller to register real user monitoring (RUM) plugins.
Type: IRumController
plugins
(since 1.19.0)
Object containing all real user monitoring (RUM) plugins embedded on the site.
dynamicBlocks
(since 1.19.0)
Holds metadata about Dynamic Blocks.
Type: undefined | DynamicBlockMetadata
processScriptQueue
Processes the next scripts from the remote document until the breakpoint script is reached.
Parameters:
breakpoint
- Identifier of the next external js.
Type: undefined | (breakpoint?: string, recursive?: boolean) ⇒ void
executionTime
(since 1.20.0)
The time when the snippet got executed.
Type: number
makeScriptExecutable
(since 2.1.0)
Clones the given script which will be executed when added to the current document.
Parameters:
script
- The script element which should be executed by the current document.
Type: (script: HTMLScriptElement, stripAttributes: boolean, enableCookieBotHandling: boolean) ⇒ HTMLScriptElement
replaceBlock
Replaces the old block with the new block in the given DOM. In contrast to replaceChild, this function makes sure that visual elements are replaced correctly, e.g. SVGs und no-script tags.
Parameters:
oldBlock
- The old block to merge.
newBlock
- The corresponding new block.
Type: (oldBlock: HTMLElement, newBlock: HTMLElement) ⇒ void
markAsMerged
(since 2.11.0)
Marks the block as merged. Use this in case of merging without replaceBlock.
updateDevice
Updates the device type set by the config or determined by SpeedKit.
bypassDeactivation
(since 2.3.0)
Activates bypassing deactivation mechanism of Speed Kit.
activate
(since 2.3.0)
Locally activates Speed Kit.
Type: () ⇒ void
deactivate
(since 2.3.0)
Locally deactivates Speed Kit.
Type: () ⇒ void
disabled
(since 2.4.0)
Indicates whether Speed Kit is disabled within config.
Type: boolean
getHash
(since 2.5.0)
Hashes an input string salted with a local salt.
simulateOfflineMode
(since 2.6.0)
Simulates offline mode for the client.
fetchBloomFilter
(since 2.7.0)
Fetches the Bloom Filter
Type: () ⇒ void
rumPlugins
(since 2.4.0)
Object containing all real user monitoring (RUM) plugins embedded on the site.
Type: RumPlugin<T>[]
updateCookies
(since 2.11.0)
Function to update cookies in Worker.
swSupported
(since 2.11.0)
Indicates whether Service Workers are supported based on the browser.
Type: boolean
skSupported
(since 2.11.0)
Indicates whether SpeedKit is supported in this browser.
Type: boolean
screenResolution
(since 2.12.0)
Native screen resolution of the device.
Type: ScreenResolution
pageTypeEnabled
(since 2.13.0)
Whether SpeedKit is enabled for the current page type.
Type: boolean
preload
(since 2.14.0)
Prewarms the urls which are sent to the Service Worker And fetched against our AssetAPI but never against the origin.
getTrackedData
(since 2.14.0)
Returns the current tracked RUM data.
Type: () ⇒ { [key: string] => T }
setAuthToken
(since 2.16.0)
Sets authentication token query parameter from Speedkit's Global object if it is present, which in turn enforces the asset response to be from the server.
PreloadResource
url
Type: string
as
Type: ContentType
ScreenResolution
width
Type: number
height
Type: number
DynamicBlockMetadata
start
A timestamp indicating when the dynamic fetcher was started.
Type: number
originResponseStart
A timestamp indicating when the first byte of the origin document was received.
originTTFB
The TTFB of the origin document.
received
A timestamp indicating when the remote document was done loading.
status
The status of the remote document request.
Type: number
complete
A timestamp indicating when the dynamic fetcher was done merging blocks.
Type: number
dataComplete
A boolean indicating when the service worker answered the dynamic fetcher.
Type: boolean
localBlocks
Amount of local blocks within cached site.
Type: number
remoteBlocks
Amount of blocks in the origin's personalized site.
Type: number
mergedBlocks
Amount of merged blocks.
Type: number
errors
All Error that happened while merging blocks.
Type: ErrorInfo[]
setAssetList
Sets the list of external assets of a document.
Parameters:
assetList
- The list of assets in the response.
delayedDoneSignal
The id of the timer executing the done signal. This can be used to abort emitting the signal in error cases.
delayedOfflineBanner
The id of the timer showing the offline banner. This can be used to abort displaying the banner in error cases.
track
Track custom events.
Parameters:
action
- The action which triggered the custom event.
label
- The label of the custom event.
value
- The value of the custom event.
updateDevice
Sends custom device types.
changes
Details about detected changes between the cached version and the origin version of the document.
Type: ChangeInfo
comparedBlocks
Number of blocks which were compared by the change detection.
Type: number
debug
Dynamic Block Debug Information.
Type: undefined | DebugInfo[]
retries
How many retries were needed, 0 if non needed.
Type: number
hotness
Hotness of the resource.
isChangeDetectionExecuted
Whether the change detection was executed.
changeDetection
How long the change detection took.
scriptsAtRisk
Scripts at risk of not being executed by Chrome.
Type: string[]
missingSelectors
Stores the selectors and finds of dynamicBlockConfig missing from the remote document. This property is used to track outdated change detection configuration.
Type: string[]
blockingDuration
Duration of blocking script (speed-kit-dom-ready.js).
responsePreparation
Duration of response preparation timespan involving automated change detections.
mergeDuration
Duration of response preparation timespan involving automated change detections.
mergeToFrame
Duration from end of merge to start of next animation frame.
frameToPaint
Duration of the animation and paint procedure.
mergeToPaint
Duration from end of merge to end of paint.
frameToNextTask
Duration from start of the animation frame to newly scheduled task.
mergeToRelease
Duration from end of merge to release of our blocking resource.
ChangeDetection
Custom change detection to specify how dynamic blocks should be checked for differences.
find
(since 2.5.0)
advanced
The CSS Selector to identify this elements which should be compared for the change detection. In case no selector is specified the whole dynamic block will be considered as the element to compare.
compare
(since 2.5.0)
advanced
A list of properties which should be compared for the elements identified through the ChangeDetection.find option. Alternatively a CustomCompareFunction can be provided to compare the elements.
Type: undefined | string[] | (local: HTMLElement, remote: HTMLElement) ⇒ string | null
ignoreQueryParams
(since 2.10.0)
advanced
Specifies a list of query parameters to be ignored when comparing the property of the identified elements. Set to true
if all parameters should be ignored.
limit
(since 2.13.0)
advanced
Limits the number of elements to be compared from the identified elements.
EnforcedTopLevelAttribute
key
Type: string
defaultValue
Type: string
CustomDimension
name
Type: string
type
Type: "PiDimension"
| "SessionDimension"
dimensionData
UserData
userId
Type: string
sessionId
Type: string
BaseDimensions
testGroup
Type: string
piId
Type: string
navigationStart
Type: number
ClickTriggerEvent
clientX
Type: number
clientY
Type: number
ClickTriggerTarget
element
Type: Element
elementClasses
Type: string
elementId
Type: string
elementTarget
Type: string
elementUrl
Type: string
IRumController
Controlling entity for all tracking data collection and sending.
trackCustomEvent
Send custom event information (action, label and value) using a beacon.
Parameters:
action
- The action which triggered the custom event.
label
- The label of the custom event.
value
- The value of the custom event.
immediately
- Indicates whether the event should be sent directly or collapsed with other events.
withTimestamp
- Indicates whether the event should include a timestamp.
Type: (action: string, label: string, value: number, immediately?: boolean, withTimestamp?: boolean) ⇒ void
trackCustomTimer
Sends custom timer information (key and data) using a beacon.
Parameters:
key
- The key to track the data for.
data
- The data to track.
immediately
- Whether to initiate sending directly or wait for next beacon.
set
Sets the given data to the given key for tracking. Calling this method multiple times will override old value. To track multiple values per key use append
Parameters:
key
- The key to track the data for.
data
- The data to track.
immediately
- Whether to initiate sending directly or wait for next beacon.
mode
- Whether to send without check if data was already sent in previous beacon.
Type: (key: string, data: T, immediately?: boolean, mode?: boolean | SendMode) ⇒ boolean
setTiming
Sets the given data to the given key for tracking relatively to the navigationStart when it is numeric. Otherwise it will be tracked normal. Calling this method multiple times will override old value. To track multiple values (without being calculated relatively) per key use append.
Parameters:
key
- The key to track the data for.
data
- The data to track.
immediately
- Whether to initiate sending directly or wait for next beacon.
mode
- Whether to send without check if data was already sent in previous beacon.
Type: (key: string, data: T, immediately?: boolean, mode?: boolean | SendMode) ⇒ boolean
append
Appends the given data to the given key for tracking. This method can be called multiple times to add multiple data items to the key.
Parameters:
key
- The key to add the data to.
data
- The data to add to the tracking.
immediately
- Whether to initiate sending directly or wait for the next beacon.
getTrackedData
Public method to get the current tracked RUM data
Type: () ⇒ { [key: string] => T }
onDOMInteractive
Ensures the callback is executed after the DOMContentLoaded event.
onLoad
Ensures the callback is executed when the document is completed.
Parameters:
callback
- The callback to execute when the document is loaded.
onSpeedKitLoaded
Ensures the callback is executed after the dynamic fetcher is done.
onDataLayer
Ensures the callback is executed when there is a new data layer event.
The callback function will be called with the data layer event as parameter.
onGaReady
Ensures the callback is executed when the GA is ready.
onGaTracking
Ensures the callback is executed when the GA tracks an event.
The callback function will be called with the data layer event as parameter.
onDataLayerReady
This method can be used to subscribe to any new populated dataLayer on the window object.
Note that subscribed observers can be notified multiple times on the same page, when the dataLayer is overwritten by a new one. The callback function will be called with the current dataLayer instance as parameter.
Parameters:
callback
- The callback which will be invoked with new dataLayer instance.
onDfDataReady
Ensures the callback is executed after the dynamic fetcher has relevant data.
onVisibilityHidden
Ensures the callback is executed after the visibility state changes to hidden.
onLeavePage
Ensures the callback is executed when the user leaves the page.
onClick
Ensures the callback is executed after a click event.
The callback function will be called with ClickTriggerEvent and ClickTriggerTarget as parameter.
onNextTick
Ensures the callback is executed in next JS-Tick (end of actual event queue).
onSoftNavigation
Ensures the callback is executed for softnavigation trigger.
onBFCacheNavigation
Ensures the callback is executed after bfCache.
getSelector
Returns an accurate selector for an element in the DOM.
Parameters:
el
- The element.
sel
- The starting selector. Used to loop through the DOM.
Type: (el: HTMLElement) ⇒ string | null
triggerSoftNavigation
Soft navigations can trigger this function to execute callbacks associated to page lifecycle.
getHardNavigation
Returns the pointer to hard navigation page impression.
Type: () ⇒ RumImpression
TrackingInstance
trackCustomEvent
Send custom event information (action, label and value) using a beacon.
Parameters:
action
- The action which triggered the custom event.
label
- The label of the custom event.
value
- The value of the custom event.
immediately
- Indicates whether the event should be sent directly or collapsed with other events.
withTimestamp
- Indicates whether the event should include a timestamp.
Type: (action: string, label: string, value: number, immediately?: boolean, withTimestamp?: boolean) ⇒ void
trackCustomTimer
Sends custom timer information (key and data) using a beacon.
Parameters:
key
- The key to track the data for.
data
- The data to track.
immediately
- Whether to initiate sending directly or wait for next beacon.
set
Sets the given data to the given key for tracking. Calling this method multiple times will override old value. To track multiple values per key use append
Parameters:
key
- The key to track the data for.
data
- The data to track.
immediately
- Whether to initiate sending directly or wait for next beacon.
mode
- Whether to send without check if data was already sent in previous beacon.
Type: (key: string, data: T, immediately?: boolean, mode?: boolean | SendMode) ⇒ boolean
setTiming
Sets the given data to the given key for tracking relatively to the navigationStart when it is numeric. Otherwise it will be tracked normal. Calling this method multiple times will override old value. To track multiple values (without being calculated relatively) per key use append.
Parameters:
key
- The key to track the data for.
data
- The data to track.
immediately
- Whether to initiate sending directly or wait for next beacon.
mode
- Whether to send without check if data was already sent in previous beacon.
Type: (key: string, data: T, immediately?: boolean, mode?: boolean | SendMode) ⇒ boolean
append
Appends the given data to the given key for tracking. This method can be called multiple times to add multiple data items to the key.
Parameters:
key
- The key to add the data to.
data
- The data to add to the tracking.
immediately
- Whether to initiate sending directly or wait for the next beacon.
getBeaconIndex
Returns the current beacon index or 0 if no beacon has been sent yet.
Type: () ⇒ number
calculateRelative
Calculates a given timer relative to the navigation start.
Parameters:
timer
- The timer which should be calculated as relative.
PerformanceTimings
A performance timings object which holds properties of the new navigation timing API as well as the deprecated one.
domLoading
Type: number
navigationStart
Type: number
ttfb
Type: number
TrackingOptions
performanceOnly
(since 2.5.1)
Prevents Speed Kit from storing user and session IDs.
stripAllParameter
(since 2.5.1)
Strips all parameter of URLs when sending data via RUM tracking. Afterwards the URL looks like this: https://www.baqend.com/page?redacted
.
stripParameters
(since 2.7.0)
Strips individual parameter of URLs when sending data via RUM tracking. Afterwards the URL looks like this: https://www.baqend.com/page?redacted-0¬filtered=foo
.
noCookies
(since 2.5.1)
When activated, Speed Kit does not use cookies to store data.
noTracking
(since 2.5.1)
When activated, Speed Kit does not send any tracking data.
dataLayer
Option to specify a custom data layer property if the customer does not use 'dataLayer'.
EcActionField
id
step
revenue
EcPurchase
actionField
Type: undefined | EcActionField
transaction_id
value
tax
shipping
currency
coupon
items
Type: undefined | []
EcCheckout
actionField
Type: undefined | EcActionField
products
RumPlugin
type
The type of the reported plugin data. If not specified the reported plugin data is treated as `Data`.
Note: If the plugin is supposed to send custom dimension or custom timer data, the key attribute must also be set, because it is needed to send custom data to the data server.
Type: undefined | "PiDimension"
| "SessionDimension"
| "Data"
| "CustomTimer"
| "SoftNavigation"
key
The key which should be used to report the plugins data. When using RumPlugin.track
this is optional, because the key will be set manually when calling the RumController
.
on
Either a known TriggerFunction which is provided by the RumController
or a custom function. If no TriggerFunction is provided the given Trackfunction
is executed directly.
Type: undefined | "domInteractive"
| "load"
| "speedKitLoaded"
| "dataLayer"
| "dataLayerReady"
| "visibilityHidden"
| "dfDataReady"
| "leavePage"
| "gaReady"
| "gaTracking"
| "click"
| "nextTick"
| "softNavigation"
| "bfCacheNavigation"
| "navigation"
| (cb: Function) ⇒ void | (cb: (args: any[]) ⇒ T | null, controller: RumController) ⇒ void
set
A function which returns a value or a list of values to be tracked immediately. If the function is called multiple times by the TriggerFunction the data will be overridden.
Note: define either RumPlugin.set
or RumPlugin.append
or RumPlugin.setTiming
since only one can be used at a time.
append
A function which returns a value or a list of values to be tracked immediately. If the function is called multiple times by the TriggerFunction the data will be appended.
Note: define either RumPlugin.set
or RumPlugin.append
or RumPlugin.setTiming
since only one can be used at a time.
track
A custom track function with direct access to the RumController
. This should be used if the plugin provides data for more than one key or advanced tracking logic is required.
Parameters:
controller
- The RumController instance.
Type: undefined | (controller: RumController, args: any[]) ⇒ void
setTiming
A function which returns a relative value or a list of relative values to be tracked immediately. If the function is called multiple times by the TriggerFunction the data will be overridden.
Note: define either RumPlugin.set
or RumPlugin.append
or RumPlugin.setTiming
since only one can be used at a time.
shouldExecute
A function which returns, whether the Plugin should be executed or not. This should be implemented if, for example, there are some execution dependencies/restrictions for a particular use case.
ReferrerMetadata
An object of metadata about the user's last navigate referrer.
referrer
The URL of the navigate request.
Type: string
url
The URL of the navigate request.
Type: string
NavigateMetadata
An object of metadata about the user's last navigate request.
firstLoad
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
url
The URL of the navigate request.
Type: string
browser
The browser which performed the navigate request.
Type: string
browserVersion
The major version of the browser which performed the navigate request.
Type: number
minorVersion
The minor version of the browser which performed the navigate request.
Type: number
timings
Holds an object of Service Worker timings of the navigate request.
Type: undefined | ServiceWorkerTimings
cdnBackendTime
The time duration of a Fastly cached asset.
cdnPoP
The point of presence as location of the Fastly cached asset.
splitTestId
ID to identify the active split test.
Type: string
group
The active split test group the user belongs to.
Type: string
responseCause
(since 1.19.0)
Describes what caused the navigate.
responseSource
(since 1.19.0)
Describes what caused this navigate.
Type: string
applicationState
(since 1.20.0)
The state of the Service Worker responsible for the last navigation.
Type: undefined | ApplicationState
errorMessage
(since 1.20.0)
The message of the error of the Service Worker responsible for the last navigation.
originStatus
(since 2.2.0)
Shows the status code of the last navigation if the origin response was served.
disconnectCause
(since 2.3.3)
Indicates the reason why Speed Kit has been disconnected.
Type: undefined | DisconnectCause
assetTTFB
(since 2.4.0)
The time to first byte of the assetApi response.
originTTFB
(since 2.10.0)
The time to first byte of the origin response.
assetSource
(since 2.4.0)
Describes the source of the assetApi response (only set if race with origin response was lost).
assetCause
(since 2.11.0)
Describes the Response Cause of the assetApi response (only set if race with origin response was lost).
Type: undefined | BasicResponseCause | CacheMissResponseCause | CacheHitResponseCause | BfCacheResponseCause
redirectList
(since 2.12.0)
List to trace back how the user got to the page.
Type: undefined | { , }[]
variation
(since 2.13.0)
Variation used to request the current navigation.
activationStart
(since 2.17.0)
The time between when a document starts prerendering and when it is activated.
noBfCacheReasons
(since 2.17.0)
The reasons why the navigated page was blocked from using the bfcache.
preloadFailureCause
(since 2.17.0)
The reason why a preload might have failed.
originResponseStart
(since 2.17.0)
Response start of the origin response.
swBooted
(since 2.17.0)
A flag to mark the initial installation of SpeedKit
Type: boolean
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.
eventStart
(since 1.20.0)
The timestamp in milliseconds when Speed Kit received the navigate request event.
Type: number
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.
blacklistHandler
The timestamp in milliseconds when the BlacklistHandler started.
disabledPageHandler
The timestamp in milliseconds when the DisabledPageHandler started.
customFetchStart
The timestamp in milliseconds when the custom fetch request started if done.
customFetchEnd
The timestamp in milliseconds when the custom fetch request ended if done.