Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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

Solution 2:

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

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

Solution 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.

Solution 4:

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

Post a Comment for "Javascript Jquery Change Src Of A Script Using A Script"