寻求IFrame源刷新方案:点击切换源后脚本致空白页问题
Fixing IFrame Refresh Issues (Blank Page Problem)
Let's break down what's going wrong with your current code and fix it step by step:
What's Causing the Blank Page?
- Redundant & Conflicting Element Selection: You're grabbing the iframe twice (
getElementById('frame')andquerySelector('iframe.reload')) for the same element—this isn't an error on its own, but it introduces unnecessary complexity. - No Check for Empty SRC: When your page first loads, the iframe has no
srcvalue. Your interval runs immediately and sets the iframe'ssrcto an empty string, which loads a blank page. - Browser Caching: Even if you had a valid
src, setting it to the same value again might not trigger a refresh because browsers cache static content.
Corrected Code
First, fix the HTML structure (your <li> elements should be wrapped in a <ul> for valid semantics):
<section id="schedules"> <div class="container"> <ul> <li><a href="./schedules/1_monday.html" target="frame">Monday</a></li> <li><a href="./schedules/2_tuesday.html" target="frame">Tuesday</a></li> <li><a href="./schedules/3_wednesday.html" target="frame">Wednesday</a></li> <li><a href="./schedules/4_thursday.html" target="frame">Thursday</a></li> <li><a href="./schedules/5_friday.html" target="frame">Friday</a></li> <li><a href="./schedules/6_saturday.html" target="frame">Saturday</a></li> <li><a href="./schedules/7_sunday.html" target="frame">Sunday</a></li> </ul> <iframe class="reload" name="frame" id="frame" frameborder="0" width="1200" height="700"></iframe> <script> // Grab the iframe once (more efficient than querying DOM every 3 seconds) const scheduleFrame = document.getElementById('frame'); window.setInterval(function() { // Only refresh if the iframe has a valid source set if (scheduleFrame.src) { // Add a timestamp parameter to bypass browser caching const cacheBustedSrc = scheduleFrame.src + (scheduleFrame.src.includes('?') ? '&' : '?') + 'refresh=' + Date.now(); scheduleFrame.src = cacheBustedSrc; } }, 3000); </script> </div> </section>
Key Improvements Explained
- Single Element Reference: We store the iframe in a variable once, so we don't waste resources querying the DOM every 3 seconds.
- Empty SRC Guard: The
if (scheduleFrame.src)check ensures we only attempt to refresh when the iframe actually has content loaded (after a user clicks a day link). - Cache Busting: Adding a unique timestamp as a query parameter forces the browser to re-request the page instead of using the cached version, guaranteeing a real refresh.
内容的提问来源于stack exchange,提问作者Michael Williams
相关产品推荐
相关产品推荐

