Failed to load resource

I used Algolia and it’s weird that when first opening the website, I always got the error message

[Error] Failed to load resource: the server responded with a status of 404 () (instantsearch.production.min.js.map, line 0)
[Error] ReferenceError: Can't find variable: algoliasearch
	Global Code (user.js:5)

However, if I refresh the page, the error will be gone. Please try cooktoday.us/dai

I use Safari browser

I use Express framework + Google Firebase Hosting. When the user hit the user route,
I call return res.render('user', {uid:req.params.id, user:user});

The View engine used is pug. I imported instantSearch and algoliasearch in user.pug file

html
  head
    script(async, defer, src="https://cdn.jsdelivr.net/npm/instantsearch.js@4.8.3")
    script(async, defer, src="https://cdn.jsdelivr.net/npm/algoliasearch@4.5.1/dist/algoliasearch-lite.umd.js")
    script(async, defer, src="/js/user.js", id="uid", uidvalue= uid)

Then in my javascript file user.js I called algoliasearch and instantsearch widgets.

Any help is appreciated! Thanks.

I guess the problem is that the async feature so the user.js was run before algoliasearch

But I am still trying to figure out the correct way to do it.

Indeed, you are correct, the issue here is the async keyword.

Async scripts must be independent from one another: https://javascript.info/script-async-defer#async
This is not the case in this situation as your user.js script depends on the InstantSearch and AlgoliaSearch scripts.

You can either:

  • remove the async attribute
  • bundle the InstantSearch, Algolia and your user script together using a bundler like webpack and serve that instead. This package will be self-contained so it can use the async keyword.

I hope that helped!
Best,

Thanks! This is super helpful. One follow up question if you don’t mind.

From the performance perspective, which approach is better? Will bundling the script together make the page load quicker?

Thanks!

I couldn’t possibly comment :slight_smile:

It really depends on what you want to achieve and what you are optimizing for. If you are using InstantSearch as an autocomplete panel that is secondary, and already have content to display on the page, it might make more sense to have everything bundle together and loaded asynchronously.

If you render your page content through InstantSearch (e.g. for a search results page), it might make more sense to have only the defer and not the async. This will not block the initial rendering/parsing of the dom, but will make it so that processing of these critical JS files is prioritized right after that.

So, the answer is it depends !

1 Like