javascript - Improve AJAX response handling function -
this code handles response rss feed. organizes , appends content. if there's video embedded separate rest of content. review on performance/efficiency i'm open other suggestions well. star selector nagging me don't know of better way iterate on contained elements.
function getfeed(url, element, callback) { $.getjson("https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+encodeuricomponent(url), function(response) { var content = "", $element = $(element); (var = 0; < response.responsedata.feed.entries.length; i++) { content = content + response.responsedata.feed.entries[i].content; //join feed entries } $element.find(".content").html(content).addclass($element.find("embed").length? "withvideo" : ""); $element.find("*").each(function() { var $this = $(this); $this.removeattr("style width align"); //reset crap comes response if ($this.is("embed")) { $element.append("<div class='video'></div>"); $this.attr("width", 640).attr("height", 360).parent().appendto(element + " .video"); }; }); if (typeof callback === 'function') { callback(); }; }); }
this called so:
getfeed("http://www.kent.k12.wa.us/site/rss.aspx?pageid=3854", "#techexpo", optionalcallback);
here's response might like
<div width="500" style="whatever"><p>some text blah blah blah.</p> <p align="right">some more text</p> </div> <div><h2>video title</h2> <embed src="http://..." width="360" height="202" type="application/x-shockwave-flash"></embed> <small>watch 7th annual tech expo highlights.</small></div>
first: don't use ".length" inside statement. way count number of items during every pass in loop.
var responsecount = response.responsedata.feed.entries.length; (var = 0; < responsecount, i++) { ... }
secondly, i'm not sure idea (performance-wise @ least):
$element.find("*")
you definately can optimize this!
performance/efficiency goes further going on single function. if not used properly, jquery can cause large performance hit. depending on scope of project, try following:
- consider version jquery 2.* smaller , faster (but lacks backwards compatibility)
- consider using custom build of jquery.
- do browsers in application's scope support queryselector ? if so, don't need jquery...
- consider lazyloading code scripts speed loading time of page
this website contains pretty checklist further reading: http://browserdiet.com/#js
Comments
Post a Comment