最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Changing "src" attribute of <script> - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Apr 10, 2012 at 15:28 KJ Saxena asked Apr 4, 2012 at 8:37 KJ SaxenaKJ Saxena 21.8k24 gold badges84 silver badges111 bronze badges 1
  • Why not just add a new script element to the dom? – Erik Philips Commented Apr 4, 2012 at 8:39
Add a comment  | 

3 Answers 3

Reset to default 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!)

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.

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.

发布评论

评论列表(0)

  1. 暂无评论