David19801
David19801

Reputation: 11448

javascript jquery change src of a script using a script

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

Answers (4)

arb
arb

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

zzzzBov
zzzzBov

Reputation: 179284

You tagged jQuery so it's really as simple as using getScript:

$.getScript(src, function () {
  console.log('script is loaded');
});

Upvotes: 3

David Thomas
David Thomas

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

Gazler
Gazler

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

Related Questions