Demogorgon
Demogorgon

Reputation: 1

JavaScript insert whole code into body?

I have tried many times to insert whole script with this code:

;
document.body.innerHTML += 'code here';

What i am trying to insert is this code example :

<script type="text/javascript">
    var adfly_id = 000;
    var adfly_advert = 'int';
    var popunder = true;
    var exclude_domains = ['example.com', 'yoursite.com'];
</script>
<script src="https://cdn.adf.ly/js/link-converter.js"></script>

Any suggestion on how could i insert this adfly script into body of content via javascript would be really appreciated.

Upvotes: 0

Views: 420

Answers (4)

Austin
Austin

Reputation: 3080

.html() does stuff like this JSFiddle Demo

$(document).ready(function () {
    $('.morebutton2').hide();

    $('#btn').on("click", function () {
        $("#st00f").html("<table style='border:solid'><tr><th>other things</th></tr></table>");
    });

});

.html literally turns the string inside of it into html syntax. You just tack it on with JQuery saying something like

$("#elementID").html("<p>stuff</p>");

Upvotes: 0

Jean-Karim Bockstael
Jean-Karim Bockstael

Reputation: 1405

You have to explicitly create the script elements then append them to the document:

// Create the element with the settings variables
var adfly_settings = document.createElement("script");
adfly_settings.setAttribute("type", "text/javascript");
adfly_settings.innerHTML = "var adfly_id = 000;\n" +
    "var adfly_advert = 'int';\n" + 
    "var popunder = true;\n" +
    "var exclude_domains = ['example.com', 'yoursite.com'];"

// Create the element with the external script
var adfly_lib = document.createElement("script");
adfly_lib.setAttribute("type", "text/javascript");
adfly_lib.setAttribute("src", "https://cdn.adf.ly/js/link-converter.js");

// Append them to the document
document.appendChild(adfly_settings);
document.appendChild(adfly_lib);

Beware that this is ugly, why can't you just append the HTML code to the page in the first place?

Upvotes: 0

zozo
zozo

Reputation: 8582

You can just put the script into the html. Literally type it there. You don't need js to include js. Also if you do it like that, the script won't actually be run at page load.

There are solutions so you can do it (like the one matt r gave), but I strongly suggest avoiding them, unless you have a good reason.

If you have any specific reason to do that, specify it so we can take it into consideration.

Upvotes: 0

Matt R
Matt R

Reputation: 734

var script=document.createElement('script');
script.type='text/javascript';
script.src="https://cdn.adf.ly/js/link-converter.js";

document.body.appendChild(script);

Upvotes: 1

Related Questions