Mats Bryntse
28 March 2018

Loading non-critical third party javascript

When building a web site or app these days, there are infinite amount of third party javascript libraries and SaaS […]

When building a web site or app these days, there are infinite amount of third party javascript libraries and SaaS services to help you. These tools can seriously accelerate your development since you don’t have to constantly reinvent the wheel. But unless you are careful, you could also introduce risk of reduced uptime of your web app due to scripts not loading correctly.

A few examples of different javascript APIs, services and tools:

Overall, the tools in this list have very little in common apart from the fact that you need load them somehow. Overall, we can divide them into two distinct categories: page-critical scripts and “the rest”.

Application critical scripts

Scripts that are critical for your page to function will of course always have to be loaded on page load. This is typically done with a good old script tag, which either includes your full application or a bootstrap JS loader that fetches the required application parts. If you build your application on Kendo or Ext JS, then you’ll definitely need to load that framework script before any other application code runs.

<script src="../../../extjs-6.5.0/build/ext-all-debug.js" type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>

or

<head>
    <title></title>
    <link rel="stylesheet" href="styles/kendo.common.min.css" />
    <link rel="stylesheet" href="styles/kendo.default.min.css" />
    <link rel="stylesheet" href="styles/kendo.default.mobile.min.css" />

    <script src="js/jquery.min.js"></script>
    <script src="js/kendo.all.min.js"></script>
</head>

The rest – non critical scripts

Any scripts that don’t fit into the critical category above can be seen as ‘nice-to-have’ scripts. If the chat service or error monitoring service that you use are unavailable (for whatever reason) – your application should still function normally. This means we should not load such scripts the same was as our critical scripts. An example, if you simply add a script to your page for a third party error monitoring service, you could just load it using a regular script tag:

<script src="https://cdn.trackjs.com/releases/current/tracker.js">
</script>

This is actually a real example from an error tracking service. Using it this way, you have now made your site vulnerable to server outage of the third party CDN. If you run an online web shop, surely you never want your shop to be offline just because the error monitoring service isn’t functioning. A better example of how to load non-critical scripts is the Google Analytics bootstrap code:

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'https://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

This assures the script is loaded async, and the site will continue to function even if the Google Analytics server would be hacked, DDoS’ed or just simply be non-responsive.

Loading scripts async

For scripts that aren’t required to bootstrap your application, you can use the ‘async’ attribute of the script tag. This will avoid the script from blocking the page load process. If you need to run code after an async script has loaded, use the script ‘load’ event:

<!-- COOKIE CONSENT -->
<script>
    window.initCookieConsent = function(){
        window.cookieconsent.initialise({
            "palette": {
                "popup": {
                    "background": "#eee", 
                    "text": "#999"
                },
                "button": {
                    "background": "#bbbbbb",
                    "text": "#ffffff"
                }
            },
            "theme": "classic",
            "content": {
                "message": "This website uses cookies to ensure you get the best experience."
            }
        })
    };
</script>
<script async onload="initCookieConsent()" src="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.3/cookieconsent.min.js" crossorigin="anonymous"></script>
<!-- EOF COOKIE CONSENT -->

Testing your site with broken scripts

If you’re not sure how your website will react to script X not being served, you can use the great Chrome Dev tools to block it. Open the Network tab in Chrome, and right click the script and select “Block request URL” then reload the page.

Now when the page is reloaded, you’ll see the script being blocked and you can inspect your page to make sure it still functions normally.

As we use RootCause to monitor bugs in all our javascript products, we tested all our sites to assure they would still be running even if there was some server outage. We hope you found this post useful, and please let us know if you have any feedback or additional tricks to make web pages load faster.

Mats Bryntse

Tips 'n tricks