3

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.

1
  • don't change the src, just add a new script. Commented Nov 6, 2011 at 23:07

4 Answers 4

5

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';
Sign up to request clarification or add additional context in comments.

1 Comment

What about if I have another js file that depends of the 'myjs.com/js.js'? How to avoid the undefineds?
3

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

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

Comments

3

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.

1 Comment

You're missing a ) . Should be $('<script>').attr({ src: 'www.google.com', type: 'text/javascript'}).appendTo('body')
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.