Including Extra Javascript Files

Sometimes when writing javascript for use with Max/MSP I find I need to reuse bits of code that I’ve already created for a different project. Most of the time a simple search, copy and paste suffices but in some situations it would be better to have the ability to import other javascript files to get access to all of the functions they contain. This would also be useful when trying to organise where you files are stored. I don’t always want my javascripts in the Max search path (too many files here will cause the program to take ages to load), and I don’t always want them in the same directory as my main patch (which is the default place Max will look for a javascript/abstraction/image). The following code will import a specified javascript file into the current one.

You can use absolute or relative paths, the comment in the code gives you examples of how to navigate through directories in both directions. Please be a bit careful as the code takes advantage of the eval() function so if one of the files you include contains a mistake or something that is badly formatted then this will be included as it exists already. You should save this file in the Cycling ’74 > jsextensions folder so it will be available any time you need it.

I don’t have Max6 yet so I cannot check, however there are numerous JSON parsing libraries available that you could use instead. I think there are even a few examples posted to the forum. If you download that example it should be fairly easy to copy the relvant code across to use instead. Let me know how it goes!

I had to do this to get my includes to be recognised. Did you have it working without this? Also I need to define my functions in the included JS with lambda-style syntax:

someNewFunction = function (a, b) { …

…rather than…

function someNewFunction(a,b) { …

Manually having to specify the scope isn’t ideal as it isn’t really about scope but about giving include() access to the global scope’s “patcher” property. Any other scope, such as one from within an anonymous function I believe will cause an error. And of course, it’s also about making sure the included functions are part of the global namespace.

There doesn’t seem to be a way to avoid the parameter by inferring the global scope directly from within include(). I tried “this” (different than “scope”) and “this.caller” (error)…