Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.load doesn't execute javascript with document.write

Tags:

jquery

ajax

load

I am trying to use jQuery.Load to load an ad call that has a document.write, and for some reason its not able to, or in firefox atleast, reloads the page with the entire ad.

Here is the simplified version of the code.

DynamicLoad.html

<html>
<head>
<script src="http://www.prweekus.com/js/scripts.js?3729212881" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Load of Script</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
   google.load("jquery", "1.3.2");
</script>
<script type="text/javascript">
   $(document).ready(function(){
    $("#myButton").click(function() {
        $("#myDiv").load("source.html");
    });
   });
</script>
</head>
<body>
<button id="myButton">Click Me</button>
<div id="myDiv"></div>

<div id="slideAdUnit"></div>

</body>
</html>

Source.html

<script language="javascript" type="text/javascript">
  document.write('<script language="javascript" type="text/javascript"><\/script>');
</script>
test

Once you click the button in FF the browser just waits for something to load. Any thoughts ?

Eventually I would be passing a src element in the document.write which points to our ad server.

Thanks for your help.

like image 623
Garfield Avatar asked Apr 13 '10 16:04

Garfield


2 Answers

You can't use document.write after the page has finished loading: it will replace the contents of the page if you do.

The easiest way to load a script dynamically with jQuery is:

$.getScript( url );

Another way is to create a new <script> element and add it to the document.

like image 103
interjay Avatar answered Sep 19 '22 00:09

interjay


writeCapture.js (full disclosure: I'm the author) can solve this:

$("#myDiv").writeCapture().load("source.html");
like image 31
noah Avatar answered Sep 19 '22 00:09

noah