5

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.

1
  • Why not just add a new script element to the dom? Commented Apr 4, 2012 at 8:39

3 Answers 3

15

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

Sign up to request clarification or add additional context in comments.

1 Comment

i know this is an old answer, but do you have any links to support this. I'm having a similar problem and nothing works so far. any reading materials regarding this would certainly help.
3

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.

1 Comment

"since script tags can't have id's," Sure they can, whatever makes you think otherwise?!
3

Whilst, yes, this is possible, you don't need to do this manually as jQuery has good built-in support for JSON-P requests. See the documentation for the $.getJSON and $.ajax methods.

3 Comments

This is not the question. The question is "can you change the src at all if the script tag is pre-existing?"
Nice gratitude. Read your question again; it read like someone wanting to do JSON-P but thought they had to do it manually. If you want to do it manually, see Aram's answer.
Not a matter of not having gratitude - you interpreted the question wrong. The question was not about how to do JSONP in JQ, it was a technical point about changing script src. Your answer was not helpful.

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.