Reputation: 11448
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.com"></script>
I want to change the url above to a different url using javascript/jquery.
Upvotes: 3
Views: 18122
Reputation: 7863
A jQuery solution to dynamically inject a JavaScript file
$('<script>').attr({
src: 'www.google.com',
type: 'text/javascript'}).appendTo('body')
This will create a new script tag with a source pointing to www.google.com and append it to the body tag.
Upvotes: 3
Reputation: 179284
You tagged jQuery so it's really as simple as using getScript
:
$.getScript(src, function () {
console.log('script is loaded');
});
Upvotes: 3
Reputation: 253506
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);
Upvotes: 0
Reputation: 84190
A pure JavaScript way to inject a script tag (at the bottom of the tag).
document.body.appendChild(document.createElement('script')).src='http://myjs.com/js.js';
Upvotes: 5