5

I am trying to understand the internal process of getScript. I am aware that it uses $.get method interally.I was thinking that jQuery puts a script tag reference into the DOM for being able execute that js file but I couldn't find script references of loaded scripts by getScript in the DOM .

So how does jQuery execute loaded scripts without script tag references in the DOM?

$.getScript('gallery.js') is exactly same thing with $('<script src="gallery.js">').appendTo('body') ?

oivvio
  • 3,026
  • 1
  • 34
  • 41
Freshblood
  • 6,285
  • 10
  • 59
  • 96

2 Answers2

7

This is the interesting part in the source code.

jQuery seems to just receive the text and evaluates it in global scope:

converters: {
    "text script": function( text ) {
        jQuery.globalEval( text );
        return text;
    }
}

In case you load the script from a different domain, jQuery adds a new script tag:

head.insertBefore( script, head.firstChild );

but removes it once the code was loaded:

// Remove the script
if ( head && script.parentNode ) {
    head.removeChild( script );
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
5

Luke, use the source.

(note these links are to an old commit)

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 1
    @ZMorek yes. This answer is 18 months old, and jQuery has continued active development. I've updated to link to a revision from back then. – Matt Ball Feb 25 '13 at 18:05
  • @MattBall - can/would you update it again please? :) – vsync Oct 04 '18 at 13:58
  • You _found_ the source, but I don't know that you've _used_ the source to answer "how". And that's really the most important part of the source: the _using_. Anybody can just find them (though I have to admit I'm really happy that you did). (apologies [to Jerry](https://www.imdb.com/title/tt0697648/characters/nm0000632)) – ruffin Oct 01 '20 at 17:20