开发者

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 ja开发者_运维技巧vascript are there any good alternatives?

My site is made C# asp.net.


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.


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/


Interesting question. You could probably use ajax with a callback and do some sort of timeout by which you'd take some action if it hasn't loaded by then. Is there a particular reason for depending on another site though? It seems a lot simpler to copy it to your site directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜