[Solved] Write a js script in a div


Don’t use document.write, it does not do what you think it does. What it does not do is write some data at the end of the document. What it does instead, is pipe data into the current write stream. And if there is no write stream, it will make a new one, resetting the document’s content. So calling document.write(dam) means you just wiped your document. document.write is a low level JS function from an earlier era of JavaScript, don’t use it.

Instead, you want to use modern DOM manipulation functions, so in jQuery, that’s stuff like:

$(document.head).append($("<script>").attr("src", url));

where

$("<script>")

builds a new script element,

$(...).attr("src", url)

sets the “src” attribute to what you need it to be, and:

$(document.head).append(...)

or

$(document.body).append(...)

to get the script loaded into your document. If it’s a plain script with src attribute, it can basically go anywhere, and if it’s a script with text content that should run, you can only make that happen through document.head.

Although if it’s just a script you need to load in and run, you can use getScript, but then you don’t need to do anything else, it’s just:

var url = "https://code.jquery.com/jquery-1.10.2.js";
jQuery.getScript(url);

Done, jQuery will load the script and execute it. Nothing gets returned.

Of course, the code you’re showing is loading jQuery, using jQuery, so that’s kind of super-odd. If you just want to load jQuery on your page, obviously you just use HTML:

<!doctype html>
<html>
  <head>
    ...
  </head>
  <body>
    ...
    <script src="http://https://code.jquery.com/jquery-1.10.2.js"></script>
  </body>
</html>

with the script load at the end so the script load doesn’t block your page. And then finally: why on earth are we loading jQuery version 1.x instead of 2.x? (if you need to support IE8: that’s not even supported by Microsoft anymore, so you probably don’t need to).

And finally, if we don’t want to load the script, but we really just want its content, as plain text, there’s only a million answers on Stackoverflow already that tell you how to do that. With jQuery, that’s:

$.get("http://https://code.jquery.com/jquery-1.10.2.js", function(data) {
  $(document.body).append($("div").text(data));
});

But you knew that already because that’s been asked countless times on Stackoverflow and you remembered to search the site as per the how to ask instructions before asking your question, right?

3

solved Write a js script in a div