zlog
zlog

Reputation: 3316

What alternatives are there to document.write?

I'm trying to load a zoom.it script dynamically, but I can't seem to do so without document.write. The problem with document.write is that it replaces everything on my page, which I don't want. What other alternatives are there?

This is document.write in action: http://jsfiddle.net/JyT9B/6/ (notice the element that gets removed).

Also, putting the <script> tag straight into the body works: http://jsfiddle.net/gTcRw/5/, but I need it to be dynamically placed.


I've also tried the methods in Ways to add javascript files dynamically in a page, and How to add and remove js files dynamically, but seem to get the error Cannot set property 'innerHTML' of null, which is probably a zoom.it specific thing. I wouldn't mind knowing why this is the case.

The jsfiddle examples of using the other approaches:

Also tried this in vain: .innerHTML - it gets added to the dom but isn't run.

Upvotes: 0

Views: 1679

Answers (2)

zlog
zlog

Reputation: 3316

Ended up using an iframe to contain a html page with an embedded script tag.

The benefit of an iframe is that I can show/remove it at will, without having to worry about cleaning up the current page document when removing the script.

ie,

HTML

<body>
  <div id="container">
    <a id="show" href="#">show</a>
    <a id="close" href="#">close</a>

    <div id="placeholder"></div>
  </div>
</body>​

JavaScript

function appendFrame(elem) {
  var iframe = document.createElement("iframe");
  iframe.id = "iframe";
  iframe.setAttribute("src", "about:blank");
  iframe.style.width = "200px";
  iframe.style.height = "200px";
  $(elem).append(iframe);
}

function loadIFrame() {
  appendFrame($("#placeholder"));

  var doc = document.getElementById('iframe').contentWindow.document;
  doc.open();
  doc.write("<html><head><title></title></head><body><script src='http://zoom.it/aaa.js'><\/script><\/body><\/html>");
  doc.close();
};

$("#show").click(function() {
  loadIFrame();
});

$("#close").click(function() {
  $("#iframe").remove();
});​

JSFiddle solution here: http://jsfiddle.net/7KRcG/2/

Upvotes: 1

Ian
Ian

Reputation: 50905

I think the combination of createElement and appendChild should work, in something like this:

http://jsfiddle.net/kbDny/3/

$(function() {
    getScript("http://www.zoom.it/aaa.js");
});

function getScript(src) {
    var scr = document.createElement("script");
    scr.type = "text/javascript";
    scr.src = src;

    var head = document.getElementsByTagName("head")[0];
    head.appendChild(scr);
}

But there's no reason to not use $.getScript - just pass the url as the first argument, like:

$.getScript(url, function (data, textStatus, jqxhr) {
    // Script loaded successfully
});

Upvotes: 2

Related Questions