Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing "src" attribute of <script>

Is it possible to change the "src" attribute of an existing <script> element using Jquery.attr()? It seemed like a simple way to get JSONP to work but I am not able to make this work for me.

like image 545
KJ Saxena Avatar asked Apr 04 '12 08:04

KJ Saxena


People also ask

What is the use of src attribute of script element?

The src attribute specifies the URL of an external script file. If you want to run the same JavaScript on several pages in a web site, you should create an external JavaScript file, instead of writing the same script over and over again.

Does script src go in head or body?

The <script> TagScripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.

Is src an attribute or property?

The src attribute specifies the location (URL) of the external resource.


2 Answers

It turns out that a script's src can only be set once! It is not possible to change the src attribute of an existing <script> element in the DOM. However, a dynamically created <script> element can have its source set (but exactly once!)

like image 183
KJ Saxena Avatar answered Oct 02 '22 19:10

KJ Saxena


If you're trying to load a script, you could instead use getScript.

http://api.jquery.com/jQuery.getScript/

Or, if you want to change the src for another reason, since script tags can't have id's, you could either use an HTML5 compliant data-id attribute, or match using the existing src. Then you could just change the src value using attr. But this may not load the script on all browsers.

like image 22
Aram Kocharyan Avatar answered Oct 02 '22 19:10

Aram Kocharyan