If you want to load an external JavaScript (.js) file into Twine 2, you can use something like the following code:
if (window.hasOwnProperty("storyFormat")) {
// Change this to the path where your HTML file is
// located if you want to run this from inside Twine.
setup.Path = "C:/Games/MyGameDirectory/"; // Running inside Twine application
} else {
setup.Path = ""; // Running in a browser
}
setup.JSLoaded = false;
importScripts(setup.Path + "YourExternalCode.js")
.then(function() {
setup.JSLoaded = true;
}).catch(function(error) { // eslint-disable-line
alert("Error: Could not find file 'YourExternalCode.js'.");
}
);
Just change "C:/Games/MyGameDirectory/" to the directory where your HTML and JavaScript files are located, and change "YourExternalCode.js" to the name of the JavaScript file you want to access.
The code doesn't get loaded immediately by importScripts(), so you can check the value of "setup.JSLoaded" (set in the above code) to tell if it has loaded properly yet or not before executing any code which depends on that JavaScript. For example:
var IntervalID = 0;
if (setup.JSLoaded) {
SomeFunction();
} else {
clearInterval(IntervalID);
IntervalID = setInterval(JSWait, 100); // Starts waiting for external JavaScript to load.
}
function JSWait() { // Checks to see if JavaScript has loaded yet.
if (setup.JSLoaded) {
clearInterval(IntervalID); // Stop waiting
SomeFunction();
}
}
function SomeFunction() {
// Your code that depends on the loaded JavaScript here.
}
That code checks to see if the external JavaScript has loaded yet or not, and if it hasn't, then it waits until it has before triggering the "SomeFunction()" function.
Also note that your external files will need to put "SugarCube." in front of SugarCube functions and properties. So if you had code that used "State.variables" to get SugarCube variables, then in the external JavaScript you'd have to do "SugarCube.State.variables" instead.
That said, the simpler solution to deal with lots of JavaScript is to just use an external editor (like Visual Studio Code), and copy and paste it into the JavaScript section from that editor. (I used to use Notepad++ for this too, but VSCode has extensions to check your JavaScript code. I recommend the "DeepScan", "ESLint", "JSHint", and "Numbered Bookmarks" extensions.)
Hope that helps! :-)