jqueryxmlhttprequestgetscriptscript-element

Force jQuery.getScript to use SCRIPT elements, never XHR


This old answer (circa. 2009) indicates that jQuery.getScript changes behavior depending on if the requested script resource / URL is domain-local or not1.

While it does provide a work-about (and there is no shortage of examples to load JavaScript elements dynamically online), I am looking for a "2014+ jQuery 1.9/2" approach to avoid using XHR/AJAX for all "get script" requests, including those that may be domain-local.

Is it possible to force jQuery.getScript (or a similar "jQuery" function) to load external JavaScript via a SCRIPT element, even for local requests?

Without much of a hack..? If the answer is "this can't be done with standard jQuery", then that's suitable and I'll pick one of the various alternative implementations.


1 Is this previous question/answer event relevant today? A quick glance at the source makes it appear that XHR is always used. The jQuery documentation shows a $.ajax equivalency, and the callbacks are all provided with a jqXHR parameter..

getScript: function( url, callback ) {
   return jQuery.get( url, undefined, callback, "script" );
},

Solution

  • As of jQuery 1.9 (and likely a long bit before), the request done by $.getScript is always done via XHR and never via <scrip> element. The linked "old" answer is indeed outdated and is no longer accurate.

    There are many examples of how to manually use a <script> element available online - but there is nothing "standard" in a modern jQuery that directly supports this.