0

I need jQuery.js, so because I don't know how to declare an "include" or "require" within my custom.js, I just paste the whole jQuery.js inside my custom.js, above my code. That makes a pretty huge custom.js script and is most likely redundant if the client already has jQuery.js loaded. Is there a way to "include" or "require" jQuery.js at the top of my custom.js? I have never found an single-file answer to referencing one .js file from another .js file.

Here is the pseudocode for the functionality sought:

Contents of original custom.js:

$(document).ready(do stuff);

Pseudocode of contents of custom.js modified to test if jQuery.js is loaded, and if not, load it:

if !jQuery {
  includeAndOrLoadEtc jQuery.js;
}

$(document).ready(do stuff);
Guessed
  • 417
  • 1
  • 4
  • 15

1 Answers1

1
if(!window.jQuery) {
   var script = document.createElement('script');
   script.type = "text/javascript";
   script.src = "jquery.js";
   document.getElementsByTagName('head')[0].appendChild(script);
}
Pik_at
  • 1,459
  • 9
  • 14
  • [script.type is not necessary](http://stackoverflow.com/a/4101482/761202), especially specifying an obsolete mime type. You can avoid the if by using [a logical or](https://github.com/h5bp/html5-boilerplate/blob/master/dist/index.html#L26). – AD7six Mar 02 '15 at 17:08