DEV Community

Cover image for Handling External JS Files in a React Website
Afroza Nowshin
Afroza Nowshin

Posted on

Handling External JS Files in a React Website

The JS files that we integrated with our React app that we are building from a template, sometimes don't work in the current setup(blog link).

If you pay attention to the website in localhost:3000, you can see that the JS doesn't work properly but rather works if you refresh the page. Why is that?


In the image, the current year is not showing as the associated Javascript has not been loaded. If you refresh the page, the year will appear.

You are loading all the scripts when you add the scripts inside public/index.html . When you are navigating all the pages, all the Javascript codes that are written for every element of the website are removed from the virtual DOM. If you refresh the page, Javascript works. Again, refresh or change to another page; Javascript is not working.

At first when I came across this weird scenario, I was unsure what was happening. I noticed that the copyright year is not visible without a refresh or page change, so I tried to add vanilla Javascript to fix that. Then I noticed the pattern, and it hit me. Somehow, the JS files are getting removed as a result of which the JS functions are not always working.

How to solve this?

Load the plugin and main JS files when the components are inserted into the virtual DOM, that is, inside the componentDidMount(). That way, whenever you change between pages or refresh the app, the JS files are loaded into the virtual DOM of that component. Install loadjs and import into your components.

yarn add loadjs

Enter fullscreen mode Exit fullscreen mode

Now, inside each page component, load the necessary JS files using this function before mounting the component:

import loadjs from "loadjs";

componentDidMount() {
Enter fullscreen mode Exit fullscreen mode

Now all the external JavaScript files will be mounted when component is mounted in the DOM without refreshing.

If you follow these posts, you have learned some tricks and tactics that you probably had to scour through Stack Overflow and Github discussion. Whether you want to build Dunder-Mifflin Infinity v20.0 or a React app from static web page materials, these techniques may come in handy. The code for can be found on my Github -

Top comments (0)