Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure offsite javascript doesn't impede site performance?

I need to include an offsite javascript file on my page, however I don't want it to be able to affect the performance of my site, in case the server where the javascript is on is down or not responding.

What I'd like to know, is if it's posible with javascript to make some sort of wrapper function to ensure that the page where the offsite javascript is hosted is responding within an acceptable timeframe.

I've considered adding the "defer" attribute to where I include the javascript, but that would as far as I know still leave the site hanging after the rest of the page is loaded.

If it's not possible to do in javascript are there any good alternatives?

My site is made C# asp.net.

like image 729
storeandersfn Avatar asked Nov 02 '10 14:11

storeandersfn


2 Answers

If the offsite JavaScript is self-contained - i.e. none of your scripts depend on it being loaded before they can function properly - the solution can be quite simple. This example is with jQuery, but any library (or even no library) is viable:

<div id="script-placeholder"></div>
<script type="text/javascript">
$(function(){
    $('.script-placeholder').append('<script type="text/javascript" src="http://site.com/file.js"></scr'+'ipt>');
});
</script>

This will wait until your entire page is loaded, then insert a new <script> block into the empty placeholder DIV, which will trigger the browser to try to download the script. If the remote server is responding slowly or is down, the script will still take a long time or time out, but it won't block your users from using the rest of your page while it waits.

like image 138
Rex M Avatar answered Sep 28 '22 15:09

Rex M


Put the script at the bottom of your page, that'll at least defer it until after everything else has loaded.

Depending on your needs, you could even load it completely after everything else via xhr (hook into the actual window load event to wait for images too), and then dynamically inject the contents by eval()ing the response text. You'd need a proxy on your site to avoid cross-domain limitations, which might defeat your purposes, I'm not sure.

See here for details: http://www.stevesouders.com/blog/2009/04/27/loading-scripts-without-blocking/

like image 25
jvenema Avatar answered Sep 28 '22 14:09

jvenema