While developing React applications, we, at times, have to rely on third-party libraries. These libraries are mostly available through npm packages, but sometimes it requires a script
tag being placed in the <head></head>
or <body></body>
of our HTML content.
For libraries that are to be used globally across the site, placing these in our main <head></head>
is absolutely fine, but for libraries that are only used in one or a few places, placing scripts in our application’s <head></head>
can add unnecessary page load and, subsequently, a longer load time.
What Do We Do Then?
One of the many solutions can be to create a function that we can call on the pages where we need the third-party library and dynamically create and inject the <script></script>
tag into the <body></body>
of the application.
Suppose we want to integrate the Google Maps API through a script and show the map on one of our pages. Let’s look at an example:
const loadGMaps = (callback) => { const existingScript = document.getElementById('googleMaps'); if (!existingScript) { const script = document.createElement('script'); script.src = 'https://maps.googleapis.com/maps/api/js'; script.id = 'googleMaps'; document.body.appendChild(script); script.onload = () => { if (callback) callback(); }; } if (existingScript && callback) callback(); };export default loadGMaps;
Let’s try to understand what our function is doing. We begin by trying to detect whether or not we’ve already loaded Google Maps by looking for a <script></script>
tag with its id
set to googleMaps
. If we do, we stop — as there’s no need to load the library twice.
If we don’t find an; we create the script dynamically. We start by creating an empty <script></script>
tag in the memory as script
and then assign the necessary attributes to its src
and the id
to identify the script later. Finally, we append the script to our <body></body>
tag to actually load this.
Finally, we call the callback()
, if it exists, both when we’re loading the script for the first time as well as on subsequent calls when the script already exists.
Usage
import React, { useEffect, useState } from 'react'; import GoogleMap from '../GoogleMap'; import loadGMaps from '../scripts/loadGMaps.js';const Maps = (props) => { const [loaded, setLoaded] = useState(false); useEffect(() => { loadGMaps(() => { setLoaded(true); }); }); return ( <div className="maps-component"> {loaded ? <GoogleMap /> : ''} </div> ); }
When our component is beginning to mount, we’ll call our library to dynamically create and inject <script></script>
into the <body></body>
. Once it’s loaded and calls to the script.onload
function, the callback we pass here will fire and update our component’s setLoaded
value to true
.
That’s it! Isn’t it too simple not to implement?