Dynamically append script tags with parameters to bust cache

While at work recently I found myself in a postion of needing to bust the browser cache for a tag on a HTML only interface in the CMS we use.
I could include a script file, but dynamically writing the page content was a no-go. It had to be entirely in JavaScript or HTML. The information in the external file was too large to be written into the page it’s self. Plus the script files needed in the client were being regenerated by the server every 15 minutes. The data was a large list for an Ajax autocomplete control, which would be uselless if it hit the server on each keypress.

I set about trying a few solutions:

document.write ("<script...");

Yeah not ideal…

Dynamically writing script tags with parameters in is a complete pain in the arse. I gave up.

var d = new Date();
var ts = d.getTime();

var head= document.getElementsByTagName('head')[0];

// append script tag
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'closures.js?_dc=' + ts;
head.appendChild(script);

I opted for this solution, much cleaner and maybe faster? I don’t know…
However the autocomplete control needed the variables defined in this script file to generate it’s list of available items. I was using the jQuery Autocomplete plugin here with an array.

By setting an interval, I was able to have the autocomplete initialise when the data in the external script was loaded thus:

	var _interval = window.setInterval(function(){
			if(typeof _list != "undefined")
			{
				initAutoComplete();
			}		
			
	}, 300); // 300 millsecond check

This allowed the browser time to process the arrays in the external files and then initialise the autocomplete when ready…

function initAutoComplete(){
        // remove the initial please wait loading message.
	$JQ("input#autocompleter").val('Enter name....');
		
        // no longer needed.	
	window.clearInterval(_interval);	
			
	$JQ("#autocompleter").autocomplete(_list, {});

        // ...... auto complete code here.
}

Doing it this way will avoid those awful IE pop-ups “variable xxx is undefined”.

Comment if you’re stuck and I’ll try help out.

Advertisement

One Response to Dynamically append script tags with parameters to bust cache

  1. Pingback: 2010 in review | jameshd – web ramblings

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s