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
Maybe the following holds true too:
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:

How to use

includeJS(url,onload,allowCache)

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!
[comments]