views:

441

answers:

4

I have a remote JS that must appear in the head of the document. If the server is slow to respond or inaccessible, obviously this slows or prevents the page from loading. I have been searching for a simple way to set a limit of say 3 seconds (probably less) for it to give up and simply not load the functionality.

Does anyone have a simple way to do this with Javascript only?

+2  A: 

Include the .JS file after the page is done loading:

<script type='text/javascript'>
window.onload = function(){
 document.write("<script type='text/javascript' src='http://domain.com/file.js'&gt;&lt;/script&gt;");
}
</script>

Place that in the HEAD of your document, then the file will start loading when the page has finished loading.

Pim Jager
A: 

Good idea! I have considered this, but the script in question actually has to load before the onload, because it modifies the page as it loads. (and sets some CSS classes as well.) Hence the need to keep it in the head. Any other ideas?

Scott Miller
The script can still do that after page has loaded.
Pim Jager
Try to respond to answers with a comment, not another answer. And like the previous comment, if possible, you can modify the script to do this initialization in the onload function
Josh
A: 

If that is an issue, split the .js apart and have the low end css functions in the and the slow ones in the onload="";

Supernovah
A: 

If window.onload event is invoked too late for you, then just inline your javascript file directly into the page.

lubos hasko