views:

81

answers:

5

I'm making an application that draws a lot of widgets and tiles on a canvas. The core UI will be defined by a long string of characters and drawn at page load by javascript. Since that core UI is big, >250K, and never changes, whats a good way to cache that?

I know I COULD just stick it in a variable at the top of the file, but is there a more efficient way? Like if wrote:

var img = new Image(); img.src = 'moose.png'

I assume that the browser will download and cache this image, so that on subsequent requests it won't have to hit my server again. But how do I do that with a chunk of text?

EDIT: basically I'm looking for an alternative to this:

var myUI = "AAAABBBCBVBVNCNDGAGAGABVBVB.... etc. for about 20 pages";
A: 

Most static resources are cache-able by a browser. Just put your data in a .txt, .dat, .xml or whatever (even a .js) and load it with your javascript via AJAX.

Peter Bailey
so you're talking about like a JS include? could you supply an example please?
LoveMeSomeCode
@LoveMeSomeCode: heh, a "JS include" is the `<script src="cachethis.js"></script>` tag itself. You'd only need AJAX if you go with @Peter's other file suggestions such as .txt, .dat, .xml etc.
Crescent Fresh
+2  A: 

You can create a JavaScript file that contains the string of text.

var text='.....';

Then you can just include the script:

<script src="/ui.initialization.js" type="text/javascript"></script>

Followed by whatever other javascript you use to render the UI. The browser will cache the js file.

EDIT

I'm assuming you're opposed to having the long string of text inline. By moving it to a separate file, you allow the browser to cache it (if it's truly static and your server is configured with proper cache-control for static resources).

Here's some information for tweaking caching on Apache (I'm assuming you're running PHP on Apache).

Ryan Emerle
thanks, exactly what i was looking for!
LoveMeSomeCode
A: 

time to download 250K over anything above 1Mbps thruput is < 1 second .. this is an issue for you?

And the very file you are downloading that contains that javascript with 250K baggage is going to be cached itself, probably.

Scott Evernden
A: 

You can use google gears or the new HTML 5 data storage features, supported by FF 3.5 and others.

powtac
A: 

Use Google page speed or YSlow to figure out what other (HTTP) improvments you can do.

powtac