thomasfrank.se
Easier than AJAX
Januari 23, 2007
So you say you want to make remote procedure calls with ease from your web page. Let's say you just want to
- get some more javascript functions as they are needed
- or get som data fragments (JSON?) back from the server.
Maybe the following holds true too:
- you have no need to post big amounts of data back to the server
- you're not keen on running a big ajax-enabling library.
Well - then I've got a small elegant solution (0,5 kB) for you:
includeJS=function(url,onload,allowCache){
url=allowCache?url:url+'&nocache='+Math.random();
url=url.split('?').length>1?url:url.replace(/\&/,'?');
onload=typeof onload=="function"?onload:function(){};
var js=document.createElement('script');
js.setAttribute('src',url);
js.addEventListener && function(){js.addEventListener('load',onload,false)}();
js.onreadystatechange=
function(){this.readyState=='complete' && onload.call()};
document.getElementsByTagName('head').item(0).appendChild(js);
};
Step by step
Let's go through that code step by step:
- if no cache is allowed - add a random number query to url to prevent caching
- make sure there is a question mark before the query variables in the url
- if onload is not a function then make it an empty function
- create a script fragment
- set the url of the script
- add an event listener for onload to the script w3c/mozilla style
- add an event listener for onload to the script ie style
- load the script by attaching it to the head section of the document.
How to use
includeJS(url,onload,allowCache)
- url - the url should be the url to the script - the script might be dynamically created by the server depending on query variables.
- onload - if you want a function to fire when the script has loaded include it here else omit this parameter or set it to false
- allowCache - if you're loading a dynamically created script don't use this parameter (or set it to false). If you're loading a big static script several times (on different pages) you might want to consider setting this to true to speed up loading a bit.
Disclaimer
I didn't invent this. But I do use it a lot... One of the first people I saw mentioning this technique was Stoyan Stefanov in an excellent article - but he did not include the onload functionality.
Happy rpc-ing!