Sometimes, you want the external js files to be loaded asynchronously such that their loading time doesn’t impact the user experience of your site. For example, when you want to integrate google-analytics.
Which means, you will have to wait for the js file to be loaded to use any of the functions provided in the js library. There is a nice pattern which lets you bypass this.
Below is the snippet Google Analytics give you to insert in your pages.
You should notice 3 important points here:
The js file is loaded asynchronously with .sync = 1 and is being inserted into the DOM
Until the file is loaded asynchronously, all the calls to ga (for eg: ga(create..)) will push into window[‘ga’].q
The handler, in this case, ‘ga’ is being stored in window[‘GoogleAnalyticsObject’]
Once the file is loaded,
We need to flush out all the entries pushed into window[‘ga’].q, which is fairly straightforward.
And then, assign the loaded library to window[window[‘GoogleAnalyticsObject’]] such that all further calls to ga() will execute the functions defined in the library.