views:

57

answers:

3

I'd like to embed a number from another page. The remote call is small (only returns a number) but I would like the page to keep loading while the request is out. How should I do it? I'm currently doing

<span id="target">Loading ...</span>
<script>
var cb = function(data) {
    document.getElementById("target").innerHTML = data; 
}
</script>
<script src="http://webnumbr.com/webnumbrs.latest.json(callback=cb)"&gt;&lt;/script&gt;

I'm open to client side or server side changes. Just the least code for the client embed the better

A: 

I believe you are using AJAX to load the content from other page on loading the current page, make sure that your AJAX call is asynchronous, and update the "webNumbr_webnumbrs" control only after successfull completion.

Ramesh Vel
and how should I ensure it is asynchronous? I don't really want to instantiate an XMLHTTPRequest object since it will make the client code pretty large.
Paul Tarjan
+1  A: 

The "official" recommendation (see rules) is to put all JavaScript at the very bottom of the HTML file. The contents of every tag will be evaluated before rendering continues, as the outcome of the script might affect further rendering (think of document.write()).

Tom Bartel
well, I'm giving the user some embed code, so getting them to put one piece where they want the embed, and another at the bottom doesn't seem very good...
Paul Tarjan
+1  A: 

Honestly,

I think the best way may be to simply put it in an onLoad() instruction so it doesn't load until the document has fully rendered. It's similar to Tom's answer but in this case you will eliminate the majority of the DOM issues you're experiencing.

jerebear
Is that supported? Do my function in `onLoad`? I've always shyed away from that tag because it didn't feel right...
Paul Tarjan
It's fully supported and recommended for certain things. Anything that will interfere with the page rendering, or requires the page to be fully rendered before launching is a good idea to put in an onLoad statement.http://www.w3schools.com/jsref/event_onload.asp
jerebear
there are very few elements that support `onLoad()`. Can I just do `window.onLoad = function() { // stuff }`?
Paul Tarjan