Question

I know proper lazy loading usually requires using objects and a proxy pattern. I'm not there yet as a site needs some redesign. However, is there any way I can still spool out DB data to a page and speed up loading time a bit?

Was it helpful?

Solution

This can be achieved with AJAX.

When you first load a page, put place-holders where the heavy content is supposed to go. For example, use a div with a distinctive style and an animated loading image inside so visitors can clearly tell there is some more loading going on. You can generate familiar looking AJAX loading images at ajaxload.info.

Have some script at the bottom of your page that calls or binds the necessary functions to load the additional content using AJAX. You could bind the AJAX call to jQuery's .ready() for example to have the loading start as soon as the rest of the document is ready or .scroll() to start when the user scrolls over a certain element (e.g. past certain 'landmarks' on your page that separate blocks of content).

When you receive the AJAX response that contains the additional content (preferably pre-formatted as HTML in string form) replace the contents of the placeholder div with the AJAX response using .innerHTML = or jQuery's .html(). Change the style of the div if necessary using setAttribute("class","newClass") or jQuery's .attr("class","value") to replace it's CSS class.

The visitor will be able to see your full page and scroll through it while the loading is taking place. The additional content will appear when it's ready without interrupting the visitor's browsing experience. You can make this a little nicer for the eye by animating the transitions after the content injection.

If you need some additional examples of how to use AJAX to fetch content asynchronously have a look at these for the classical JavaScript approach or jQuery .ajax() docs.

OTHER TIPS

You can use JavaScript to start loading extra data as soon as the main page loads. This way your main page can just outline the components on the page, present "spinners" indicating that more data is being loaded and then offload it to JavaScript to get more data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top