最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to lazyload anything - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question asked Jan 18, 2013 at 21:30 ettaetta 35.7k84 gold badges220 silver badges329 bronze badges 2
  • 2 It seems a duplicate of stackoverflow./questions/8192651/… – Ragnarokkr Commented Jan 18, 2013 at 21:35
  • The short answer is yes. The longer answer is what have you tried? – Anthony Grist Commented Jan 18, 2013 at 21:35
Add a ment  | 

3 Answers 3

Reset to default 6

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.

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.

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./shrimpwagon/jquery-lazyloadanything

发布评论

评论列表(0)

  1. 暂无评论