Mg Gm
Mg Gm

Reputation: 151

adding a script tag dynamically with document.write

I dont know if this is a good idea but I am trying to add a script using document.write in my HTML document that would add a script only if the browser is online.

<script>
var online = navigator.onLine;
if(online){
  document.write("<script src='./api.js'></script>");
}
</script>

the thing is the browser is stoping at the first closing </script> tag that is inside the document.write function, causing everything else to be interpreted as HTML ( "); appears renedered in the html) , I know that I am doing something wrong but would like to know what

Upvotes: 1

Views: 5172

Answers (3)

Jacek Pietal
Jacek Pietal

Reputation: 2019

You could try:

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "./api.js";
document.head.appendChild(script);

also are you missing extension on api? should it be api.js?

Upvotes: 1

taggon
taggon

Reputation: 1936

Try this:

document.write("<script src='./api'></"+"script>");

You're right. Browsers read all <script> ... </script> block and pass them to JS engine. So, if you want to write </script> you should break it.

Note Using document.write to add JavaScript to document is not a good idea.

Upvotes: 2

Xspirits
Xspirits

Reputation: 217

EDIT: please see this thread and answers: https://stackoverflow.com/a/8024286/2192152

Here is a code I used for a personal website:

/* *************************************************************
 *  Loading any js file.
 ************************************************************** */
staticPath ='./js/';
vendorPath='./js/vendor/';

src = [
    {f:'jquery-1.8.3.min.js', n:1},
    {f:'jquery-ui-1.9.2.js', n:1},
    {f:'lib.js', n:0},        
];


for (var i in src)
{
    if (src[i].n === 0) document.write('<' + 'script type="text/javascript" src="' + staticPath + src[i].f + '"></sc' + 'ript>');
    else  document.write('<' + 'script type="text/javascript" src="' + vendorPath + src[i].f + '"></sc' + 'ript>');
}

As you can see you should split the string containing you script call. I unfortunately don't know much more of why this is needed.

Note: I tried many setting and the one I provide you here is the fastest one in terms of load time (using chrome)

Upvotes: 1

Related Questions