If the externalDomain is someway busy or down, our page will hang, waiting for the externalDomain. The page will eventually be loaded and displayed when the resource becomes free. Worst case scenario: the externalDomain stays busy and our page stays completely blank.
There's a solution to the above issue: using asynchronous loading and here I show you how to use it.
With asynchronous loading, your external resource will be loaded only after the loading of the page. So, we should be careful in using it, because we have to be sure that the whole page is not totally relying on that external snippet.
On the good side of things, our page will load faster and it will be always ready for the user.
The codeThe code is just a few lines:
When our page is loaded the function is inserting the external resource in async mode. Infact we set the HTML5 attribute async to true.
var asynScript = document.createElement('script');
asynScript.async = true;
asynScript.src = 'http://externalDomain.com/script.js';
var x = document.getElementsByTagName('script');
x.parentNode.insertBefore(asynScript , x);
The effectAs said above, the page will load faster, but we might end up dealing with some minor effects. For example, the asynchronous loading of the external resource could move page elements after the page is loaded, causing an unwanted "resetting" of some elements (like the sliding of a container). In other cases, some functions might be available to the user with a small delay, giving the impression that the page froze for a moment.
Those counter-effects can be solved by carefully placing the loaded content ('http://externalDomain.com/script.js') in the right spot or, for example, creating the needed space when the page loads.