Loading third party library in ReactJS
While building an application there are situations where you need to use a 3rd party JS library such as jQuery, D3.js for rendering charts, etc. Lots of packages are built and maintained by developers, organizations, and communities. The good part of using this third party library is it boost the application development process and helps to gain the goal.
There are conditions where you want to load a library for a particular component or page or maybe in a response to users actions but there is no any package in npm
.
In cases like this, preloading the whole library when the application starts is an unnecessary and expensive operation which could possibly slow down your application.
How to deal?
Let’s take the example of a widget provided by the klipfolio. In order to add klipfolio dashboard, we have to embed code to our React application.
We want to see the dashboard to a particular page of our application. Without preloading the whole library we want to load it in a specific page of react.
Now what we can do is.
Let’s break down the code. Whenever the page load at /dashboard route firstcomponentWillMount
actions gets triggered. Where we are going to load our first script.
<script type=”text/javascript” src=”https://embed.klipfolio.com/a/js/embed.api"></script>
Then after the script gets loaded we are calling the callback function and inside that callback function, we are doing computation using the previously loaded library.
script.onload = function() {
let newScript = document.createElement(‘script’);
let inlineScript = document.createTextNode(‘KF.embed.embedKlip({
profile : “your-kilpfolio-container-key”,settings : {“width”: 1141,”theme”:”light”,”borderStyle”:”square”,”borderColor”:”#cccccc”},title : “Awesome Dashboard” });’); newScript.setAttribute(‘id’, ‘klipfolioDashboard’); newScript.appendChild(inlineScript); document.getElementsByTagName(‘head’)[0].appendChild(newScript); };
Which will load our dashboard to specific div + id
. Now we need to remove our library when a user goes to other routes. Which is done in componentWillUnmount
componentWillUnmount () {
let klipfolioEmbed = document.getElementById(‘klipfolioEmbed’);
let klipfolioDashboard = document.getElementById(‘klipfolioDashboard’);
if (klipfolioEmbed && klipfolioDashboard) {
klipfolioEmbed.remove();
klipfolioDashboard.remove();
}
}
Conclusion
Thus, In this way, we can embed 3rd party libraries on demand without preloading it. This is just one-way approach there are different kinds of packages available in npm store which allows us to use 3rd party library in a specific page or route or component.
Note: To learn more about JavaScript visit https://github.com/sumn2u/learn-javascript.