2013-07-23 4 views
1

이 코드는 RSS 피드의 응답을 처리합니다. 콘텐츠를 구성하고 추가합니다. 내장 된 비디오가 있다면 나머지 컨텐츠와 분리하십시오. 주로 성능/효율성에 대한 리뷰를 원하지만 다른 제안들에 대해서도 개방적입니다. 그 스타 셀렉터는 정말로 잔소리지만, 포함 된 모든 요소를 ​​반복하는 좋은 방법을 모르겠습니다. AJAX 응답 처리 기능 향상

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); 

     for (var i = 0; i < response.responseData.feed.entries.length; i++) { 
      content = content + response.responseData.feed.entries[i].content; //Join all the 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 all the crap that comes with the 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(); 
     }; 
    }); 
} 

는 다음과 같이 호출됩니다 문에 대한 내부 ".length"를 사용하지 마십시오

getFeed("http://www.kent.k12.wa.us/site/RSS.aspx?PageID=3854", "#TechExpo", optionalCallback); 

여기에 응답이

<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 the 7th annual Tech Expo highlights.</small></div> 
+0

왜 각 노드를 반복하지 않고 jQuery 선택기 (또는 indexOf)를 사용하여 EMBED 태그를 찾으십니까? –

+0

@Diodeus하지만 응답에서 혼란을 제거하기 위해 각 요소를 반복해야합니다. –

답변

1

먼저 어떻게 보이는지입니다. 이렇게하면 루프의 모든 통과 중에 항목 수가 계산됩니다.

var responseCount = response.responseData.feed.entries.length; 
for (var i = 0; i < responseCount, i++) { 
... 
} 

둘째, 나는 이것이 아주 좋은 생각이다 모르겠어요 (성능 현명한 이상) :

$element.find("*") 

당신은 확실히이를 최적화 할 수 있습니다!

성능/효율성은 일반적으로 단일 기능으로 넘어갑니다. 제대로 사용하지 않으면 jQuery가 큰 성능 저하를 일으킬 수 있습니다. 프로젝트의 범위에 따라 다음을 시도해 볼 수도 있습니다 :

  • 버전 jQuery를 2 고려 * (호환성 거꾸로하지만 부족) 훨씬 더 작고 더 빠른되는
  • 는 jQuery를의 사용자 지정 빌드를 사용하는 것이 좋습니다.
  • 응용 프로그램의 범위 지원 querySelector에서 브라우저를 수행 하시겠습니까? 그래서, 당신은 아마 jQuery를 ... 필요하지 않은 경우
  • 는 페이지의 로딩 시간을 단축하기 위해 코드 스크립트를 lazyloading 고려해이 웹 사이트는 더 읽기 꽤 좋은 체크리스트를 포함

: http://browserdiet.com/#js