cometta
cometta

Reputation: 35679

how to lazyload anything

I know able to lazy load 'image' using some third party jquery library. Is there anyway to lazy load just about anything like <div> element container for example when user scroll to that <div> container

Upvotes: 8

Views: 13799

Answers (3)

Jeffrey Sweeney
Jeffrey Sweeney

Reputation: 6116

To expand on kinsho's (correct) answer:

For security and maintainability reasons, you should be wary of injecting raw HTML directly into documents. Doing so can break event listeners, break the DOM parser, and potentially open up security vulnerabilities.

Usually, the best way to lazy load stuff is to send encoded data (such as JSON or XML) to the client, and process the result accordingly. For basic HTML, a templating solution could be used. Even an iframe can be better than pasting <div><h1>Hello</h1><table><tbody><td><tr>1</td></tr><tr><td>2</td></tr></tbody></table></div>* into an element's innerHTML.

Also, before you implement lazy loading for your site, take some time to consider if it's really worth it. An additional HTTP request is noticeably more expensive than just downloading data all at once, and any HTML injected via Javascript will not be seen by web search crawlers. So, if you're only injecting a small amount of static information, it really isn't worth the trouble.


*can you find the parse error? Now imagine doing that for a standard-sized HTML document.

Upvotes: 6

shrimpwagon
shrimpwagon

Reputation: 905

Here is what you really wanted to begin with. It is a new jQuery plugin that I made myself. You can "Lazy Load" anything you want based on any element (jQuery selector) you wish.

https://github.com/shrimpwagon/jquery-lazyloadanything

Upvotes: 0

kinsho
kinsho

Reputation: 536

Why rely on some third-party library to help you lazy-load? You can do just fine using native JavaScript.

In fact, as long as you accept the principle that all lazy-loading is triggered by some user action, set up a listener on a specific object (be it the scroll bar, some section header, etc). Set up a corresponding handler that relies on AJAX (you can use jQuery here) to fetch data (preferably HTML) that you can load directly into whatever container you want using the innerHTML property of the container element.

Upvotes: 3

Related Questions