$(function () { const DATA_URL = "./data/cmList.json"; let videoIds = []; function buildEmbedUrl(videoId) { return `https://www.youtube.com/embed/${videoId}?rel=0&autoplay=1&mute=1`; } function collectVideoIds(json) { const awards = Array.isArray(json.awards) ? json.awards : []; const others = Array.isArray(json.others) ? json.others : []; const all = awards.concat(others); // videoIdだけ抜き出して重複排除 const ids = all.map((x) => x && x.videoId).filter(Boolean); return Array.from(new Set(ids)); } async function loadIds() { const res = await fetch(DATA_URL, { cache: "no-store" }); if (!res.ok) throw new Error(`JSON読み込み失敗: ${res.status} ${DATA_URL}`); const json = await res.json(); videoIds = collectVideoIds(json); if (!videoIds.length) throw new Error("videoId が1件も取れませんでした"); } // 先に読み込んでおく(失敗してもボタン自体は殺さない) loadIds().catch((e) => { console.error("[Randam] 初期化失敗:", e); }); $("#Randam a").on("click", async function (e) { e.preventDefault(); // まだ読み込み前ならここで待つ if (!videoIds.length) { try { await loadIds(); } catch (err) { console.error("[Randam] JSON読み込み失敗:", err); return; } } const randomIndex = Math.floor(Math.random() * videoIds.length); const videoId = videoIds[randomIndex]; const url = buildEmbedUrl(videoId); // lityがあるなら確実に開く(href差し替え方式より安定) if (typeof window.lity === "function") { window.lity(url); } else { // 保険: lity未ロードなら別タブで開く window.open(url, "_blank", "noopener"); } // 念のため href も差し替えておく(デバッグや右クリック用) $(this).attr("href", url); }); });