The following Q&A illustrates how to load a single javascript file into JavaScriptCore: https://stackoverflow.com/a/26979233/1056563
func analyzeText(scriptName: String) {
var ext = scriptName.pathExtension
var fileName = scriptName.substringToIndex(
advance(scriptName.startIndex,
scriptName.utf16Count - ext.utf16Count - 1))
if fileExtension.utf16Count == 0 {
fileName = scriptName
ext = "js"
}
let url = NSBundle.mainBundle()
.URLForResource(fileName, withExtension: ext)
let scriptCode = String(contentsOfURL: url!,
encoding: NSUTF8StringEncoding,
error: nil)!
var context = JSContext(virtualMachine: JSVirtualMachine())
context.evaluateScript(scriptCode)
/* ... */
}
What if there are many javascript files and they have interdependencies: can they be loaded sequentially in reverse order of their dependencies and expect to resolve properly?
utils.jsfile1NeedingUtils.jsfile2NeedingFile1.js
So then :
func analyzeText(jsContext: JSContext, scriptName: String) {
var ext = scriptName.pathExtension
var fileName = scriptName.substringToIndex(
advance(scriptName.startIndex,
scriptName.utf16Count - ext.utf16Count - 1))
if fileExtension.utf16Count == 0 {
fileName = scriptName
ext = "js"
}
let url = NSBundle.mainBundle()
.URLForResource(fileName, withExtension: ext)
let scriptCode = String(contentsOfURL: url!,
encoding: NSUTF8StringEncoding,
error: nil)!
jsContext.evaluateScript(scriptCode)
}
var jsCtx = JSContext(virtualMachine: JSVirtualMachine())
["utils.js","file1NeedingUtils.js","file2NeedingFile1.js"]
.forEach( x in analyzeScript(jsCtx, x))
Notice that we are sharing the same JSContext across all the invocations.
That functionality is typically the domain of the browser to handle. I am planning to go that route but am wondering if there were likely to be issues . In addition are there optimizations to the process that would be helpful?