JavaScript
iframe
web development
script loading
HTML5

Run script before iframe loads

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If you need a script to run before an iframe loads its real content, the practical solution is to delay assigning the iframe src until your setup work is finished. The important constraint is that you cannot inject arbitrary code into a cross-origin page before it loads, so the answer depends on whether you control the iframe content and when the browser starts navigation.

Understand What "Before the Iframe Loads" Means

An iframe begins loading as soon as the browser sees a src and decides to navigate it. If the markup already contains a real src, your script is racing a navigation that may already be underway.

That leads to the first rule:

  • if you need work to happen first, do not give the iframe its final src until that work is done

A common pattern is to render a placeholder iframe element without a source, run setup logic, and then assign the target URL.

html
1<iframe id="report-frame" title="Report"></iframe>
2<script>
3  async function loadFrame() {
4    const token = await Promise.resolve("abc123");
5    const frame = document.getElementById("report-frame");
6    frame.src = "/report.html?token=" + encodeURIComponent(token);
7  }
8
9  loadFrame();
10</script>

In this example, the iframe does not start loading /report.html until the token is ready.

Control the Load Sequence From the Parent Page

If your goal is analytics setup, permissions checks, or dynamic URL generation, handle that logic in the parent page and create the iframe only after the preconditions are satisfied.

html
1<div id="host"></div>
2<script>
3  function createIframe(url) {
4    const frame = document.createElement("iframe");
5    frame.title = "Preview";
6    frame.src = url;
7    document.getElementById("host").appendChild(frame);
8  }
9
10  const allowed = true;
11  if (allowed) {
12    createIframe("/preview.html");
13  }
14</script>

This approach is simple and deterministic. The script runs first because the iframe does not exist until the script creates it.

Cross-Origin Iframes Change the Rules

If the iframe points to another origin, the parent page cannot run code inside that embedded document before it loads. That is a browser security boundary, not a missing JavaScript trick.

For cross-origin content, your realistic options are:

  • compute the final URL before assigning src
  • show a placeholder or loading state in the parent page
  • coordinate through postMessage after the iframe has loaded
  • serve a wrapper page that you control, and let that page load the third-party content

If you need code to execute inside the embedded page before its main logic runs, you must control that page or at least control a wrapper page that loads it.

Same-Origin Cases Are More Flexible

When the iframe loads a page from the same origin, you can coordinate more closely. One pattern is to load a lightweight bootstrap page first and let that page perform setup before navigating to the final content.

html
<iframe id="frame" src="/frame-bootstrap.html" title="Bootstrap"></iframe>

Then inside /frame-bootstrap.html, run the setup script before redirecting.

html
1<script>
2  sessionStorage.setItem("frameMode", "compact");
3  location.replace("/real-content.html");
4</script>

This works because you control the document that loads first. It does not bypass the cross-origin model.

Use Load Events for Post-Load Coordination

Sometimes the requirement is slightly different: you do not need to run code before navigation, you need to react immediately after the iframe finishes loading. In that case, use the load event.

html
1<iframe id="profile-frame" src="/profile.html" title="Profile"></iframe>
2<script>
3  const frame = document.getElementById("profile-frame");
4  frame.addEventListener("load", () => {
5    console.log("iframe finished loading");
6  });
7</script>

That does not help with true pre-load execution, but it is the right tool for the common case of post-load initialization.

Avoid Relying on Timing Hacks

Developers sometimes try to beat the browser with setTimeout, inline script ordering tricks, or DOM mutations after the iframe is already in the page with a real src. Those approaches are fragile.

If order matters, make the order explicit:

  • render without the final src
  • do the required work
  • assign the src

That is much more reliable than hoping your script runs first in every browser and network condition.

Common Pitfalls

The most common mistake is assuming you can execute JavaScript inside a third-party iframe before it loads. You cannot unless you control that content.

Another mistake is putting a real src in the HTML and then trying to "run something first" with later scripts. By then, the browser may already be navigating.

A third issue is confusing pre-load work with post-load coordination. If you only need to know when the frame is ready, use the load event instead of redesigning the page.

Finally, if you use same-origin bootstrapping, keep the control flow clear so that one bootstrap page is not silently turning into an unmaintainable redirect chain.

Summary

  • To run code before an iframe loads, delay assigning the real src until the code has finished.
  • Creating the iframe dynamically is often the cleanest way to control the load order.
  • You cannot inject pre-load logic into a cross-origin iframe that you do not control.
  • For same-origin content, a bootstrap page can run setup before loading the final page.
  • Use the iframe load event for post-load coordination, not true pre-load work.
  • Prefer explicit load sequencing over timing hacks.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.