I need to load JavaScript code (which I don\'t have control over) from a URL into a div. The JavaScript code is a bunch of document.write() statements. Once the document.write()
You can setup an html page that has just this (in this example it's called test2.html):
You can then load this page into the DOM in an iframe and attach a load event handler that gets the contents of the page after it's done loading. This example then also removes the from the DOM:
$(function () {
//append the iframe onto the body, then select it and attach an event handler for the `load` event
$('body').append('').children('iframe').on('load', function () {
//set the html of the `mydiv` element to the body of the loaded page (test2.html)
$('#mydiv').html($(this).contents().children().children('body').html());
//remove the iframe from the DOM
$(this).remove();
//set the source of the iframe after the `load` event handler is setup to make sure it fires properly
}).attr('src', 'test2.html');
});
Here is a demo: http://apexeleven.com/stackoverflow/document.write/test.html
Note that .on() is new in jQuery 1.7 and is the same as .bind() in this case.