Reputation: 33186
I am trying to compress my JavaScript code to get less traffic on my site. It has been working fine, but now I came across an error I can't resolve.
I turned my ajax function into one line:
function(){if(xmlhttp.readyState==4&&xmlhttp.status==200){document.getElementById("content").innerHTML=xmlhttp.responseText;}}xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();}
But the chrome console tells me there is an unexpected identifier on this line. Firefox says there is an semicolon missing on this line.
I have been trying to figure out what is wrong, but I can't find the error, can someone help me with this?
Upvotes: 22
Views: 201956
Reputation: 11
If you want to compress JS, I recommend you to use Closure Compiler, a tool provided by Google for website developers. It also provides additional APIs that can be implemented by yourself
Upvotes: 0
Reputation: 12718
In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:
function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}
There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()
And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?
Upvotes: 4
Reputation: 1450
It looks like there is an extra curly bracket in the code.
function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}
Upvotes: 1
Reputation: 116664
I recommend using http://jsbeautifier.org/ - if you paste your code snippet into it and press beautify, the error is immediately visible.
Upvotes: 11
Reputation: 33637
Either remove one } from end of responseText;}}
or from the end of the line
Upvotes: 2
Reputation: 154818
Yes, you have a }
too many. Anyway, compressing yourself tends to result in errors.
function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
} // <-- end function?
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}
Use Closure Compiler instead.
Upvotes: 40