We've previously looked at getting search setup using Fuse.js. However, the example provided used an async function (`getProducts`) to request product data from Nacelle. This approach is less than optimal, as it requires a client-side call to Nacelle before search can be used. This can be both time consuming, and requires a good deal of bandwidth. Instead, we recommend creating a search.json file once, and using it to search your catalog.
Once you've created your search.json file, here are some ways you can optimize it. For reference, this particular JSON file contains 93 products, and it's original size is 535 KB.
Dropping Unused Fields
An ordinary products request from Nacelle will contain a myriad of fields that may be useful from developers, and customers. However, for search it is easy to be opinionated when determining what fields are important.
Take for example the following fields: indexedAt, createdAt, and updatedAt. Within the context of a simple search bar, these fields are unimportant. As a result we can drop them to save some space.
To start, drop all fields, except for the content object:
import data from "./search.json";
const content = data.map((item) => item.content);
With just this one change the file size has gone from 535 KB to 173 KB, a 68% drop.
Even with the all the information we've dropped, we still have access to several crucial fields required for search. This includes, the product handle, title, description, and even featured media.
Taking it a step further, within the content object unused field can be dropped:
const specific = content.map((item) => {
return {
title: item.title,
description: item.description,
handle: item.handle,
};
});
The example above is quite spartan. The only fields in the search.json file are: title, description, and handle. This takes our file size down from 173 KB to 30 KB.
Minify JSON
Minification is the process of removing some of the conveniences that make JSON more readable for humans, but aren't necessary for the computer. This includes line breaks, indentations, and spacing. By striping away formatting we can further decrease the file size.
Compression (gzip, brotli)
Compression involves compressing a file on the server, and decompressing it in the client's browser. This means that a smaller search.json file is sent, and your sites loads faster. When using gzip on our truncated JSON file, the file size dropped from 30 KB to 7 KB, a 77% reduction in size.
Setting up compression can be done in a number of ways. The most optimal way would be consult with your hosting provider's documentation.
Comments
0 comments
Please sign in to leave a comment.