ページネーションの実装(オフセット方式) — limit, offset パラメータ利用
大量のデータを一度に表示すると重くなるので、ページネーション(ページ分割表示)を使います。
初心者は「limit = 1ページに表示する件数、offset = どこから始めるか」と覚えると理解しやすいです。
基本の考え方
limit→ 1ページに表示する件数offset→ 先頭から何件スキップするか
例:
limit=10, offset=0→ 1〜10件目limit=10, offset=10→ 11〜20件目limit=10, offset=20→ 21〜30件目
基本のコード例(API 呼び出し)
const limit = 10; // 1ページに表示する件数
const page = 2; // 2ページ目を表示したい
const offset = (page - 1) * limit; // 10件スキップ
fetch(`/api/items?limit=${limit}&offset=${offset}`)
.then(res => res.json())
.then(data => {
console.log("取得したデータ:", data);
});
JavaScriptよく使うテンプレート集
ページ番号から offset を計算
function getOffset(page, limit) {
return (page - 1) * limit;
}
JavaScript次ページ・前ページボタン
let currentPage = 1;
const limit = 10;
function nextPage() {
currentPage++;
loadPage(currentPage);
}
function prevPage() {
if (currentPage > 1) currentPage--;
loadPage(currentPage);
}
function loadPage(page) {
const offset = (page - 1) * limit;
fetch(`/api/items?limit=${limit}&offset=${offset}`)
.then(res => res.json())
.then(data => console.log("Page", page, data));
}
JavaScriptサーバー側(SQL の例)
SELECT * FROM users
ORDER BY id
LIMIT 10 OFFSET 20;
→ 21〜30件目を取得。
例題: 商品一覧ページ
async function loadProducts(page = 1) {
const limit = 5;
const offset = (page - 1) * limit;
const res = await fetch(`/api/products?limit=${limit}&offset=${offset}`);
const products = await res.json();
console.log(`Page ${page}:`, products);
}
loadProducts(1); // 1〜5件目
loadProducts(2); // 6〜10件目
JavaScript- 効果: 商品一覧をページごとに分けて表示できる。
実務でのコツ
- limit は固定値にすることが多い(例: 10件/20件)。
- offset はページ番号から計算する。
- 大量データでは cursor 方式も検討(offset は遅くなる場合がある)。
- UI と連動: 「次へ」「前へ」ボタンやページ番号リンクを作る。
練習問題(ブログ記事のページネーション)
async function loadArticles(page = 1) {
const limit = 3;
const offset = (page - 1) * limit;
const res = await fetch(`/api/articles?limit=${limit}&offset=${offset}`);
const articles = await res.json();
console.log(`Page ${page}:`, articles);
}
loadArticles(1); // 1〜3件目
loadArticles(2); // 4〜6件目
JavaScript直感的な指針
- limit = 1ページの件数。
- offset = 先頭から何件スキップするか。
- ページ番号から offset を計算して API に渡す。
- 初心者は「limit=10, offset=(page-1)10」で練習すると理解が深まる。*
これを覚えれば「大量データをページごとに分割して表示」できるようになり、ブログや商品一覧などの Web アプリでよく使うページネーションを実装できます。
