0

This is driving me slightly bonkers, since it must surely be an easy thing to achieve. I've spent hours searching for the solution, but can only find a solution in the context of html (with embedded JS code).

I have a native javascript file (.js not .html), and all I want to do is to include/embed/load the code in from another javascript (library) file into that file. This is NOT html I'm talking about, it's pure unadulterated javascript. The solutions I've seen are all along the lines of http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html.

All I want to be able to do is:

include('./lib/cooljslibfile.js');
// ... now use functions etc defined in the above library file

Surely, to write re-usable code that can be deployed in multiple scripts, there must be a way other than just copying and pasting the contents of cooljslibfile.js into my javascript file?

drmrbrewer
  • 11,491
  • 21
  • 85
  • 181
  • 1
    Current JS does not support this *yet*. However, there are module loaders available today which provide such functionality. Have a look require.js and browserify (depending on your needs). – Felix Kling Oct 12 '14 at 15:17
  • Thanks, Felix. Is there a "quick and dirty" way of doing it? Like reading the external js file and dumping it into the current js file as it is interpreted? I'm sure I've seen a solution like this, but for the life of me I can't find it again, in amongst all the html-based solutions. – drmrbrewer Oct 12 '14 at 15:34
  • You could make a Ajax request and simply `eval` the response, but that's really quick and dirty ;) – Felix Kling Oct 12 '14 at 16:06
  • Something you might wanna try is to have a `javascript.php` file that has a correct MIME type header and echoes your code. Like this you can use PHP `include();` for any such thing – Kolja Oct 12 '14 at 17:27
  • OK thanks. Regarding making an Ajax request, wouldn't that require first loading in the jquery library... chicken and egg? – drmrbrewer Oct 12 '14 at 18:05
  • No, ajax calls can be made with the standard included vanilla, so it's considered pure js. Search for [XMLHttpRequest](http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery) – Matthijs van Hest Oct 23 '15 at 09:28

0 Answers0