How to reference a class and method from a javascript library included on index.html

446 views Asked by At

I have a SPA built in React. I need to include a JavaScript library for analytics from a CDN -it should not be bundled with the rest of the JS libraries.

So far I've learned that it is not webpack's job and that I should use a script loader, like scriptjs. I found this thread but I can't understand the implementation: https://github.com/webpack/webpack/issues/240.

I need to:

  1. include the JS library from the CDN. So far I've done that by referencing it on the Index.html page. (ie <script src="//path/to/cdn/utag.js"></script>)

  2. reference the library from components in the React app. There is a class utag with methods view() and link() that I need to call when buttons are pressed in the application. If I try utag.link() from within a method in a react component the object utag is not defined and react will not compile.

How can I include this library so it is accessible by all my components and how do i reference the class and methods that I need?

Thanks!

1

There are 1 answers

0
James Webley On

The script reference in the HTML is fine.

For analytics, you might want to build a wrapper into your application that handles events and tests for the availability of the downstream functions, along the lines of:

var analytics = {
  view: function(a,b,c){
    if(window.utag && window.utag.view && typeof window.utag.view == "function"){
      window.utag.view(a,b,c);
    } else {
      // handle lack of Tealium availability here
    }
  },
  link: function(a,b,c){
    if(window.utag && window.utag.link && typeof window.utag.link == "function"){
      window.utag.link(a,b,c);
    } else {
      // handle lack of Tealium availability here
    }
  }
};

You can then use analytics.view() and analytics.link() immediately, and write code to handle Tealium not having been loaded (e.g. a one second delay followed by a follow-up attempt).