1

Via jquery's $.getScript method, can you give the included script a DOM id?

So generated code should be:

<script type="text/javascript" id="xxxxxx" src="..."></script>

I know I could probably just document.write that line myself, but $.getScript must be there for a reason right? (cross browser compatibility, etc?)

Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119
  • document.write would be used before the DOM is ready. Usually jQuery methods are called after the DOM is ready. You probably meant you could just use `document.createElement("script")` – Ruan Mendes Jun 30 '11 at 17:41
  • 2
    Out of curiousity what is the purpose of adding an ID to a dynamically loaded script? – Jamie Treworgy Jun 30 '11 at 17:44
  • @jamietre ... to dynamically UNload it later! ;-D – Roko C. Buljan Jun 30 '11 at 18:10
  • Why would you do that? What purpose does it serve? The script will already have executed. It won't have any effect on objects that have been created. http://jsfiddle.net/ueFn3/ If you want to free memory, this isn't how to do it. – Jamie Treworgy Jun 30 '11 at 18:14
  • 1
    I'm using it to load a third party javascript, and in the source they seem to reference their own script by the id, that's why I needed to set it. I've now gone ahead and used the same snippet that google analytics uses (async) (no jquery) –  Jun 30 '11 at 18:19
  • Bizarre. I can't imagine why that would ever be necessary. It's not actually referencing "itself", it's just referencing some text between two script tags. Sounds like some kind of atrocious hack. – Jamie Treworgy Jun 30 '11 at 18:22
  • I've just taken a look, it seems to reference it to get a hold of the src attribute, so that it can look at ? query parameters (via regex.test).. Can't it just look at window.location itself? –  Jun 30 '11 at 18:27

1 Answers1

0

I think this has maybe been answered/discussed before here: Why call $.getScript instead of using the <script> tag directly?.

getScript allows you to dynamically load a script in situations where it's either desirable to delay the loading of the script, in situations where you want to get a status callback on when the script has been loaded or in situations where you couldn't use a script tag.

getScript has some downsides in that it's subject to the same-origin policy whereas a script tag is not.

If have seen other web pages put an ID on a script tag (smugmug.com), but I've also seen that flagged as non-standard when testing standard's compliance. It seems to work and be used by others, but I'm guessing it isn't standard.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979