I use a third party ad server to deliver the advertisements on my site. There are two invocation methods: IFRAME and JavaScript. I currently use the IFRAME method because it allows the full webpage to render independently of the ads ... in other words, without slowing down browser rendering time contacting and downloading images or flash animation from a third party server. I don't want the page content to be delayed being displayed because of a slow ad server or large flash animated ad. However, the JavaScript version is more full featured. Is there a way that I could use the JavaScript version while telling the browser not to execute it until the end? What if I were to include the JavaScript via an external file instead of inline?

Dani AI

Generated

Several answers here point in the right direction, but they leave one important gap. and described delaying execution until the page has finished loading, and suggested timeouts/innerHTML; added a placeholder div. Those tactics do defer the ad, but they do not reliably solve the hard case: many ad tags use document.write. Running a document.write after parsing will either clobber the page or fail to execute as intended. The notes below give practical, modern options and a safe shim for document.write when an async provider tag is not available.

If the remote tag does not use document.write, the cleanest options are to load it asynchronously or insert its <script> element dynamically at the ad placeholder. Example dynamic loader (works for tags that are DOM-safe):

// non-blocking loader for tags that do NOT use document.write
(function(adUrl, slotId){
  var slot = document.getElementById(slotId) || (function(){
    var d = document.createElement('div'); d.id = slotId;
    (document.body || document.getElementsByTagName('head')[0]).appendChild(d);
    return d;
  })();
  var s = document.createElement('script');
  s.src = adUrl;
  s.async = true;
  slot.appendChild(s);
})('https://adserver.example.com/tag.js','ad-slot');

If the tag uses document.write (the common blocker), a shim can capture writes, parse the returned HTML, inject DOM nodes into a placeholder and recreate any script nodes so they execute. The pattern below temporarily replaces document.write, loads the remote tag, then restores the original write function. It avoids page replacement but has important caveats (CSP, cross-origin behavior, exact execution ordering for complex tags, and provider terms).

// simple document.write shim (illustrative)
(function(adUrl){
  var slot = document.getElementById('ad-slot') || document.body;
  var nativeWrite = document.write;
  document.write = function(html){
    var doc = new DOMParser().parseFromString(html,'text/html');
    Array.prototype.slice.call(doc.body.childNodes).forEach(function(n){
      if (n.nodeName.toLowerCase()==='script'){
        var s = document.createElement('script');
        if (n.src) { s.src = n.src; s.async = false; }
        s.text = n.textContent;
        slot.appendChild(s);
      } else {
        slot.appendChild(document.importNode(n,true));
      }
    });
  };
  var s = document.createElement('script');
  s.src = adUrl; s.async = true;
  s.onload = function(){ document.write = nativeWrite; };
  (document.head||document.documentElement).appendChild(s);
})('https://adserver.example.com/tag.js');

Notes and troubleshooting: inspect the provider snippet or the remote .js to confirm whether document.write is used. If the tag is document.write‑based and the shim still breaks behavior, the safest choices are an iframe wrapper (the original approach) or requesting an async/non‑document.write tag from the ad provider. Also consider CSP and the ad network’s terms before modifying tag behavior; some providers publish an official async loader which is the preferred solution.

Recommended Answers

All 7 Replies

don't know if this is what you are looking for or if it will help, but if you call a javascript function via the onload event in the body tag, it will not run until the page is fully loaded.

<body onload="doWhatever();">

Glad to help the csgal.

Campkev is correct. Here is how I do it.

<html>
<head>
<title>My Web Page</title>
<script type="text/javascript">
function LoadTrigger()
{
  alert('This will fire after the page has finished loading.');
}
window.onload = LoadTrigger;
</script>
</head>
<body>
  <p>
	 My Web Page is great!
  </p>
</body>
</html>

Thanks, guys. Appreciate the help! I will have to play around with this because my JavaScript code uses document.writes so I need to implement them inline where they belong. :) Will work on it and let you guys know!

To ensure the page is loaded before the add is drawn you can use a setTimeout(yourfunction,500) type mechanism in the onLoad.

You can also look at using the html dom to add innerHTML instead of using document.write

This can be done at any time... you could even set up a script that rotates your adds every minute or so (also by manipulating the innerHTML of DOM nodes).

Because I'm using a third party ad server, I don't have access to the script, itself (such as editing the document.writes). All I can do is call the <script> which is located on a remote server.

CSGal, did you ever find a solution to this crazy problem? I've been wrestling with this problem as well.

Thanks!

Maybe this will work:

<html>
<head>
<title>My Web Page</title>
<script language="javascript">
function LoadTrigger(){
	document.getElementById("AdServer").innerHTML = "<iframe.....></iframe>";
}
window.onload = LoadTrigger;
</script>
</head>
<body>
<!-- Placeholder for the iframe -->
<div id="AdServer"></div>
</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.