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 to 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';
    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 existingScript; 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.

#react #front-end-development #javascript #reactjs

How to Load Third-Party Scripts Dynamically In React
20.70 GEEK