せかいや

いまいるここを、おもしろく http://sekai-in-the-box.appspot.com/

【GitHub】getJSON、GitHubAPI、を高速化して使う

 

自分のサイトはhistoryメニューで
サイトリソース全体のコミット履歴を参照できるようになっています。

面白いかなーと思って。

で、問題がひとつ。


表示がすごくおそい
ということで、表示を高速化するために修正する。


 

GitHubAPIにて、取得件数を5件で固定(デフォルト30件)

このリクエストURLにて、コミット情報が取得できる。
https://api.github.com/repos/sekaiya/sekai-in-the-box/commits

取得する件数を絞る方法は、、と探ってみたら、ページング機能があるみたい。
GitHub API v3

Requests that return multiple items will be paginated to 30 items by default. ・・・you can also set a custom page size up to 100 with the ?per_page parameter.

これにしたがって、取得URLを以下に変更。
https://api.github.com/repos/sekaiya/sekai-in-the-box/commits?per_page=5



 

getJSONのコールバックを見直し

・・・てみたけど、やっぱりこれ以上シンプルにかけない。
JavaScript はコールバック地獄だとはよく言ったもんだ。。
 
■修正前

$("#contents").load("inc/history.inc", function(){
  new_histories = $.tmpl($("#contents"), [{contents: histories}]);
  $("#contents").html(new_histories);
});

 
■修正後

$("#contents").load("inc/history.inc", function(){
 $("#contents").html($.tmpl($("#contents"), [{contents: histories}]));
});

 
そうか!
historyボタンを押された瞬間ではなくて、ロード時にすでにcommitデータを読み込んでおけばいいんだ!

jQuery(document).ready(function() {
・・・
  $.getJSON("https://api.github.com/repos/sekaiya/sekai-in-the-box/commits?per_page=5", function(res){
    histories = new Array();
    for (var i=0 ; i < res.length ; i++){
      var commit_info = new CommitInfo(new Date(res[i].commit.author.date).toLocaleString(), res[i].commit.message, res[i].html_url);
      histories.push(commit_info);
    };
  });
});

解決ー。
さっくっと表示できるようになったよ!