So, I've narrowed down my error (well, at least the first one) to this function:
var genArray = function () {
var arr, len, i;
if(arguments.length > 0) {
len = [].slice.call(arguments, 0, 1)[0];
arr = new Array(len);
for(i = 0; i < len; i++) {
arr[i] = genArray.apply(null, [].slice.call(arguments, 1));
}
} else {
return null; //or whatever you want to initialize values to.
}
return arr;
}
Then, I get a very unhelpful error:
error on line 71 at column 23: StartTag: invalid element name
Below is a rendering of the page up to the first error
Now, the function is decidedly not on line 71 (perhaps it is in the compiled ePub, but I have no idea how they correlate). Further, I have no idea what that error means in a JavaScript context. Also, this code works fine in a browser (Safari included).
Any ideas what could be causing the issue?
EDIT: On a whim, I checked whether []
was the problem by changing it to Array()
. No luck.
Okay, so I discovered a solution to my problem. I just needed to surround my JavaScript in CDATA tags like so:
//<![CDATA[
var genArray = function () {
var arr, len, i;
if(arguments.length > 0) {
len = [].slice.call(arguments, 0, 1)[0];
arr = new Array(len);
for(i = 0; i < len; i++) {
arr[i] = genArray.apply(null, [].slice.call(arguments, 1));
}
} else {
return null; //or whatever you want to initialize values to.
}
return arr;
}
//]]>
I discovered this by using the epubcheck tool which said something to the effect that the file must have properly formed characters or something. I don't recall the exact message. Anyways, this reminded me of a problem I had in a script where I used some unicode characters. I remembered about CDATA which solved it. Then I found this stackoverflow question which basically says it's necessary for when your pages must be interpreted as XML/XHTML as well, which is the case for ePubs.
So, moral of the story is wrap javascript in CDATA tags for ePubs or iBooks.
EDIT: It should be noted that it's worth doing this around all of your JavaScript. The issue in my case was the <
less than operator being interpreted as the start of a tag. However, it is probably cleaner to just include the CDATA tag around all of your JavaScript rather than trying to isolate sources of the issue.
EDIT 2: In the interest of aggregating information to whoever finds this answer useful, it should also be noted that having all of one's JavaScript in external files probably also works (according to the source linked in the answer to the question I've linked to). I don't care to test this at the moment, but it should work because the external JavaScript will not be parsed as XML like it is inside of a <script>
tag.