简体   繁体   中英

Alternative to JQuery.load()

I've been looking at this article: https://css-tricks.com/ajax-load-container-contents/

Which suggests using jQuery.load('url #container') to ajax load in a specific div within another page. But the comments are full of "yeah but this is awful for bandwidth, to load a whole page and parse out just one part". But nobody ever offers an alternative solution.

Can anyone offer a comprehensive alternative?

Depends at what level you're talking. jQuery.load was really useful for tab controls and the like when there was no better alternative. Now, there are a lot of techniques people use in order to achieve this.

The most common use cases of jQuery.load were for entire pages (eg to "fake" a MV* type functionality) or for sections of a page (eg newsfeed that you update with new content)

Entire pages

For entire pages loaded (eg a tab control) you tend to see routing libraries used, eg angular routing or perhaps a more lightweight example, Crossroads.js .

The way these work is by modifying the location hash which does not force a page refresh and then loads content from the specified template (.html) file.

The reason why this is better is that jQuery.load for pages results in an ever expanding DOM, whereas routes "clean" up after themselves by removing elements from the DOM that would no longer be "visible" on that page.

Templates within pages

The second most common use case for jQuery.load was to load content into a section of a page. The most common thing seen done here today is to use a templating library, for example, Handlebars .

The way these work are to define your markup in a script tag. You then load your content (usually JSON) from a web server or whatever and then apply the template to that JSON and append the resulting markup to the container.

The reason why this is more efficient than jQuery.load for an entire page is because you load back just the raw data needed and apply it to a known template rather than load the entire result from a page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM