大量に同じ画像を表示したいとき

画像周りの速度メモ - #生存戦略 、それは - subtechの件。

最終手段として、CSSを使う。

.hatenastar{
display:inline-block;
width:11px;
height:10px;
background:url('http://s.hatena.ne.jp/images/star.gif');
}
(function(){
var now = new Date*1;
for (var i = 0; i < count; i++) {
  var span = document.createElement('span');
  span.className = 'hatenastar';
  container.appendChild(span);
}
document.title += ' css:' + ((new Date*1) - now);
})();

テストページ http://ss-o.net/test/star.html

一応クロスブラウザでかなり高速に(Firefoxでは500msが100msくらいに)動くけど、IE6で表示を整えるが面倒。あと、cloneNodeとDocumentFragmentも使えばもっと高速化できるclone+fragmentなパターンも追加。全体的に速くなったけど、それほど大きな違いではない。あと、console.profileが使える環境ではprofileするオプションを追加。

ちなみに、id:amachangが試したときに逆に遅くなっていたのは、backgroundImage経由で指定していたからだと思うけど、その辺は未検証。

追記:大量の同じ画像の表示 - 素人がプログラミングを勉強していたブログについて。

background-repeatって発想はなかった。冴えてるなぁ。
で、実際にはスクロールを考慮する必要があって少し面倒で、適当にクロスブラウザ*1にするとこんな感じ。
http://ss-o.net/test/star_repeat.html
実際にはdoctypeでの(document.documentElement or document.body)分岐とgetBoundingClientRect未実装ブラウザへの対応とか、あと大事なのが端数への対応ってのがある。ちょっと頑張れば実用化できそう。

*1:手抜きでgetBoundingClientRect使ったから、Safariは未対応だけど、WebKitエンジンでもWebKit NightlyやGoogle ChromeのDevリリースなら動く