I have a javascript script. It has a src element to it. This src is a url, and I would like to change it using javascript, just once to something else, or create it dynamically.
What's the best way to create a script element dynamically using javascript/jquery?
I have:
<script type="text/javascript" src=""></script>
I want to change the url above to a different url using javascript/jquery.
I have a javascript script. It has a src element to it. This src is a url, and I would like to change it using javascript, just once to something else, or create it dynamically.
What's the best way to create a script element dynamically using javascript/jquery?
I have:
<script type="text/javascript" src="http://www.google."></script>
I want to change the url above to a different url using javascript/jquery.
Share Improve this question asked Nov 6, 2011 at 22:59 David19801David19801 11.4k26 gold badges86 silver badges127 bronze badges 1- don't change the src, just add a new script. – zzzzBov Commented Nov 6, 2011 at 23:07
4 Answers
Reset to default 5A pure JavaScript way to inject a script tag (at the bottom of the tag).
document.body.appendChild(document.createElement('script')).src='http://myjs./js.js';
You tagged jQuery so it's really as simple as using getScript
:
$.getScript(src, function () {
console.log('script is loaded');
});
A jQuery solution to dynamically inject a JavaScript file
$('<script>').attr({
src: 'www.google.',
type: 'text/javascript'}).appendTo('body')
This will create a new script tag with a source pointing to www.google. and append it to the body tag.
I'd suggest using something like this:
var head = document.getElementsByTagName('head')[0];
var newScript = document.createElement('script');
newScript.src = 'http://path.to/script.js';
newScript.type = 'text/javascript';
head.parentNode.appendChild(newScript);