How to Append <Script></Script> in JavaScript

How to append script/script in JavaScript?

Try this:

var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://somedomain.com/somescript";
$("head").append(s);

Note that the script will load and you can access the variables inside it, but you wouldn't see the actual <script> tag in the DOM.

How to append script/script to div and execute it?

ESCAPE the "/" of closing tags

<script>
dialogFun();
function dialogFun(){

var code = "<div style='font-size: 12px' id='dialog'>"+
"<script src='https://content.jwplatform.com/libraries/xyz.js'><\/script>"+
"<div id='jwplyr'>Loading the player...</div>"+
"<script type='text/javascript'>jwplayer('jwplyr').setup({'file': 'http://content.jwplatform.com/videos/xyz-lusPHdHK.mp4','image':'http://content.jwplatform.com/thumbs/xyz-320.jpg'});<\/script><\/div>";

console.log(code);
$( "body" ).append( code );
}
</script>

Can't append script element

I've seen issues where some browsers don't respect some changes when you do them directly (by which I mean creating the HTML from text like you're trying with the script tag), but when you do them with built-in commands things go better. Try this:

var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#someElement").append( script );

From: JSON for jQuery

Append script into div using jquery

It all because about the parsing problem. The problem showing up after found </script> this code. It's assume we want to close the script tag but we won't. In order to avoid that, put \ before / like so to escape special character :

$(document).ready(function() {
var tag = '<script src="xxx.js"><\/script>'; // file to grab images
var tag2 = '<img src="some image link"></img>';
$('#test').append(tag); //testing
$('#test2').append(tag2); //testing
});

DEMO

Try inspect the element in chrome to see the code.

Executing a script tag on append after the DOM has loaded

On a whim I made this change:

// document.getElementById('scriptMe').appendChild(s);
document.body.appendChild(s);

and boom, script runs and video loads.

Which is super interesting, because "why", right?

Edit:
In addition, trying other script injection methods discussed here.

document.write method

document.write(s.outerHTML) // s is a script node

also works. In fact, you can embed that script node in a div and it works as well.

createContextualFragment method

// var $container = document.getElementById('scriptMe'); // does not work
var $container = document.body
var range = document.createRange()
$container.appendChild(range.createContextualFragment(script_str))

works, where script_str is an html string literal. This will work both as "<script>....</script>" or "<div id="myDiv"><script>...</script></div>"

but all the methods I tested ultimately needed injection to be done in body.

codepen

appending script src=/script to head based on screen width

See it in action: Short Demo


You can define a function, like this:

function appendScript(pathToScript) {
var head = document.getElementsByTagName("head")[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.src = pathToScript;
head.appendChild(js);
}

And then call it with the appropriate argument (e.g. according to screen size), like this:

appendScript("path/to/file.js");

If you also need to remove a script from head (e.g. based on its 'src' attribute), you can define a function, like this:

function removeScript(pathToScript) {
var head = document.getElementsByTagName("head")[0];
var scripts = head.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var js = scripts[i];
if (js.src == pathToScript) {
head.removeChild(js);
break;
}
}
}

And then call it with the appropriate argument (e.g. according to screen size), like this:

removeScript("path/to/file.js");

Also, note that using screen.width returns the size of the user's screen (not the browser-window's width).

If you need to get the window size you can use $(window).width() (using jQuery).
If you want a "jQuery-free" solution, take a look at this answer for cross-browser alternatives.

Add/append 'script' tag to html using javascript/jquery

Instead of writing out the script tag directly, create it as an object and then append it. The browser should respect it when you've created the element directly instead of passing it a string.

var script = document.createElement( "script" );
script.type = "text/javascript";
script.src = "scriptname.js";
$("#temp").append(script);

Then you can just put the javascript you want to execute in the external script file and it should work fine



Related Topics



Leave a reply



Submit