Improve performance for Vue InstantSearch
On this page
Algolia is fast by default. But network speed and bandwidth can vary. This page lists a few best practices you can implement to adapt to your users’ network conditions.
Prepare the connection to Algolia
When sending the first network request to a domain, a security handshake must happen, consisting of several round trips between the client and the Algolia server. If the handshake first happened when users typed their first keystroke, the speed of that first request would be significantly slower.
Use a preconnect link to carry out the handshake immediately after loading the page but before any user interaction.
To do this, add a link tag with your Algolia domain in the head
of your page.
1
2
3
4
<link crossorigin href="https://YOUR_APPID-dsn.algolia.net" rel="preconnect" />
<!-- for example: -->
<link crossorigin href="https://B1G2GM9NG0-dsn.algolia.net" rel="preconnect" />
Add a loading indicator
Consider a user accessing your app in a subway:
- They type some characters
- Nothing happens
- They wait, but still, nothing happens
However, you can enhance the user experience by displaying a loading indicator to indicate something is happening.
To display a loading indicator in the ais-search-box
, use the show-loading-indicator
option. The indicator will display slightly after the last query has been sent to Algolia. Change the duration of the delay with stalled-search-delay
(on the ais-instant-search
widget).
For example:
1
2
3
4
5
6
7
8
9
<template>
<ais-instant-search
index-name="instant_search"
:search-client="searchClient"
:stalled-search-delay="200"
>
<ais-search-box show-loading-indicator />
</ais-instant-search>
</template>
Make your own loading indicator
You can also use the loading indicator in custom widgets. The following example shows how to make a custom component that writes Loading...
when search stalls. If network conditions are optimal, users won’t see this message.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!-- components/LoadingIndicator.vue -->
<template>
<div v-if="state && state.searchMetadata.isSearchStalled">
<p>Loading…</p>
</div>
</template>
<script>
import { createWidgetMixin } from 'vue-instantsearch';
const connectSearchMetaData =
(renderFn, unmountFn) =>
(widgetParams = {}) => ({
init() {
renderFn({ searchMetadata: {} }, true);
},
render({ searchMetadata }) {
renderFn({ searchMetadata }, false);
},
dispose() {
unmountFn();
},
});
export default {
name: 'AisStateResults',
mixins: [createWidgetMixin({ connector: connectSearchMetaData })],
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<template>
<ais-instant-search
index-name="instant_search"
:search-client="searchClient"
:stalled-search-delay="200"
>
<ais-search-box />
<app-loading-indicator />
</ais-instant-search>
</template>
<script>
import AppLoadingIndicator from './components/LoadingIndicator'
export default {
components: {
AppLoadingIndicator,
},
}
</script>
Debouncing
Another way of improving the perception of performance is by preventing lag. Although the default InstantSearch experience of generating one query per keystroke is usually desirable, this can lead to a lag in the worst network conditions because browsers can only make a limited number of parallel requests. By reducing the number of requests, you can prevent this lag.
Debouncing limits the number of requests and avoid processing non-necessary ones by avoiding sending requests before a timeout.
Implement debouncing at the ais-search-box
level with the connectSearchBox
connector. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<template>
<input type="search" v-model="query" />
</template>
<script>
import { connectSearchBox } from 'instantsearch.js/es/connectors';
import { createWidgetMixin } from 'vue-instantsearch';
export default {
mixins: [createWidgetMixin({ connector: connectSearchBox })],
props: {
delay: {
type: Number,
default: 200,
required: false,
},
},
data() {
return {
timerId: null,
localQuery: '',
};
},
destroyed() {
if (this.timerId) {
clearTimeout(this.timerId);
}
},
computed: {
query: {
get() {
return this.localQuery;
},
set(val) {
this.localQuery = val;
if (this.timerId) {
clearTimeout(this.timerId);
}
this.timerId = setTimeout(() => {
this.state.refine(this.localQuery);
}, this.delay);
},
},
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<ais-search-box index-name="instant_search" :search-client="searchClient">
<app-debounced-search-box :delay="200" />
</ais-search-box>
</template>
<script>
import AppDebouncedSearchBox from './components/DebouncedSearchBox.js'
export default {
components: {
AppDebouncedSearchBox,
},
}
</script>
Find the complete source code on GitHub.
This code has been specifically created for Vue 2. Some modifications may be required for it to work correctly in Vue 3.
Optimize build size
InstantSearch supports dead code elimination through tree shaking, but you must follow a few rules for it to work:
- Bundle your code using a module bundler that supports tree shaking with the
sideEffects
property inpackage.json
, such as Rollup or webpack 4+. - Make sure you pick the ES module build of InstantSearch by targeting the
module
field inpackage.json
(resolve.mainFields
option in webpack,mainFields
option in@rollup/plugin-node-resolve
). This is the default configuration in most popular bundlers: you only need to change something if you have a custom configuration. - Keep Babel or other transpilers from transpiling ES6 modules to CommonJS modules. Tree shaking is much less optimal on CommonJS modules, so it’s better to let your bundler handle modules by itself.
If you’re using Babel, you can configure babel-preset-env
not to process ES6 modules:
1
2
3
4
5
6
7
8
9
10
11
// babel.config.js
module.exports = {
presets: [
[
'env',
{
modules: false,
},
],
],
}
If you’re using the TypeScript compiler (tsc
):
1
2
3
4
5
6
// tsconfig.json
{
"compilerOptions": {
"module": "esnext",
}
}
Import only what you need, and avoid using the plugin (Vue.use(VueInstantSearch)
) plugin. Doing so imports all the widgets, even the ones you don’t use.
Instead, individually import and register each InstantSearch widget within components:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<template>
<div id="app">
<ais-instant-search :search-client="searchClient" index-name="indexName">
<ais-search-box></ais-search-box>
<ais-hits></ais-hits>
</ais-instant-search>
</div>
</template>
<script>
import algoliasearch from 'algoliasearch/lite';
import { AisInstantSearch, AisSearchBox, AisHits } from 'vue-instantsearch';
export default {
components: {
AisInstantSearch,
AisSearchBox,
AisHits,
},
data() {
return {
searchClient: algoliasearch('YourApplicationID', 'YourWriteAPIKey'),
};
},
};
</script>
With this approach, only the manually imported widgets end up in the production build, and tree shaking removes the rest.
You can also register InstantSearch widgets at the app level:
1
2
3
4
5
6
7
8
9
10
11
import Vue from 'vue';
import { AisInstantSearch, AisSearchBox } from 'vue-instantsearch';
import App from './App.vue';
Vue.component(AisInstantSearch.name, AisInstantSearch);
Vue.component(AisSearchBox.name, AisSearchBox);
new Vue({
el: '#app',
render: (h) => h(App),
});
Troubleshooting
To check if tree shaking works, try to import InstantSearch into your project without using it.
1
import 'vue-instantsearch' // Unused import
Build your app, then look for the unused code in your final bundle (for example, “InstantSearch”). If tree shaking works, you shouldn’t find anything.
Caching
Caching by default (and how to turn it off)
By default, Algolia caches the search results of the queries, storing them locally in the cache. This cache only persists during the current page session, and as soon as the page reloads, the cache clears.
If users type a search (or part of it) that’s already been entered, the results will be retrieved from the cache instead of requesting them from Algolia, making the app much faster.
While it’s a convenient feature, sometimes you may want to clear the cache and make a new request to Algolia. For instance, when changes are made to some records in your index, you should update your app’s frontend to reflect that change (and avoid displaying stale results retrieved from the cache).
The refresh
function, available for custom connectors, lets you clear the cache and trigger a new search.
When to discard the cache
Consider discarding the cache when your app’s data is updated by:
- Your users (for example, in a dashboard). In this case, refresh the cache based on an app state, such as the last user modification.
- Another process you don’t manage (for example, a cron job that updates users inside Algolia). In this case, you should refresh your app’s cache periodically.
Refresh the cache triggered by a user action
The following code triggers a refresh based on a user action (such as adding a new product or clicking a button).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<template>
<button @click="refresh">refresh</button>
</template>
<script>
import { createWidgetMixin } from 'vue-instantsearch';
const connectRefresh =
(renderFn, unmountFn) =>
(widgetParams = {}) => ({
init() {
renderFn({ refresh() {} }, true);
},
render({ instantSearchInstance }) {
const refresh = instantSearchInstance.refresh.bind(instantSearchInstance);
renderFn({ refresh }, false);
},
dispose() {
unmountFn();
},
});
export default {
name: 'AisStateResults',
mixins: [createWidgetMixin({ connector: connectRefresh })],
methods: {
refresh() {
this.state.refresh();
},
},
};
</script>
Use it within your app as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
<ais-instant-search
index-name="instant_search"
:search-client="searchClient"
:stalled-search-delay="200"
>
<ais-search-box />
<app-refresh />
<ais-hits />
</ais-instant-search>
</template>
<script>
import AppRefresh from './components/Refresh.js'
export default {
components: {
AppRefresh,
},
}
</script>
Find the complete source code on GitHub.
This code has been specifically created for Vue 2. Some modifications may be required for it to work correctly in Vue 3.
Refresh the cache periodically
You can set an interval to determine how often the app clears the cache. Use this approach if you can’t trigger cache clearance based on user actions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<template>
<button @click="refresh">refresh</button>
</template>
<script>
import { createWidgetMixin } from 'vue-instantsearch';
const connectRefresh =
(renderFn, unmountFn) =>
(widgetParams = {}) => ({
init() {
renderFn({ refresh: {} }, true);
},
render({ instantSearchInstance }) {
const refresh = instantSearchInstance.refresh.bind(instantSearchInstance);
renderFn({ refresh }, false);
},
dispose() {
unmountFn();
},
});
export default {
props: {
delay: {
type: Number,
default: 10000, // (10 seconds)
},
},
name: 'AisStateResults',
mixins: [createWidgetMixin({ connector: connectRefresh })],
mounted() {
this.timerId = setInterval(() => {
this.state.refresh();
}, this.delay);
},
destroyed() {
if (this.timerId) {
clearInterval(this.timerId);
}
},
};
</script>
If you need to wait for an action from Algolia, use waitTask
to avoid refreshing the cache too early.
Queries per second (QPS)
Search operations aren’t limited by a fixed “search quota”. Instead, they’re limited by your plan’s maximum QPS and operations limit.
Every keystroke in InstantSearch using the ais-search-box
counts as one operation.
Then, depending on the widgets you add to your search interface,
you may have more operations being counted on each keystroke.
For example, if you have a search interface with an ais-search-box
, an ais-menu
, and an ais-refinement-list
,
then every keystroke triggers one operation.
But as soon as a user refines the ais-menu
or ais-refinement-list
,
it triggers a second operation on each keystroke.
If you experience QPS limitations, consider implementing a debounced ais-search-box
.