How to load a script in rescript-react?

I would like to figure out a way to load third party scripts such as Google Places Autocomplete.

So far my approach is going to be using this recipe https://usehooks.com/useScript/ and translating it into rescript. I wonder if there is any other more performant way.

We have done this a lot, and found that it really depends on your tech stack. For example, a static site generator might have you specify third-party scripts in a config file, and if you’re using Helmet.js, then you might need to use bindings to their API.

For many situations, you can just add the script tag to the HTML file (inside <head> or <body>), and it will work. Just depends on the bundler/code-generator you use (if any), and your requirements.

It might help if you discuss the specific tech stack you are using.

hey @austindd
I use NextJS. I could load the script from the document.js or using the <Next.Head> tag.
The problem is that since this is a script that it is only used in certain views, I just want to lazy load it.
Therefor I was thinking about using a hook

Right, I think due to the way script tag loading/execution is handled after the HTML document has been parsed, you will inevitably need some JavaScript to handle it, unless you load a new document from scratch.

You could always try to tune the performance of the JavaScript, but the implementation you linked to is probably the approach I would take.

I just saw that NextJS is working on a new component next/script for this exact use case.

3 Likes

Still not fully converted to pure ReScript, but here’s the module that is responsible for the rescript-lang playground bundle loading: https://github.com/reason-association/rescript-lang.org/blob/master/src/common/CompilerManagerHook.res#L13

(we basically attach a <script/> to the dom, and wait for a loaded event… when we switch compiler bundles, we remove the original script tag beforehand)

pretty good for lazy loading stuff on user interaction etc

3 Likes

another solution https://github.com/bettercart/rescript-react-script-loader

2 Likes