Friday, March 4, 2011

Best way to cancel a slow loading remote JS call

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?

From stackoverflow
  • 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'></script>");
    }
    </script>
    

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

  • 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?

    Pim Jager : The script can still do that after page has loaded.
    Josh : 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
  • 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="";

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

0 comments:

Post a Comment