Alex G Alex G - 6 months ago 46
jQuery Question

Check syntax of JavaScript(jQuery) code before running jQuery.globalEval() or eval()

Continuing with topic: jQuery .globalEval() function

I use jQuery.globalEval(varwithJScode);

Now the problem starts when code in varwithJScode contains syntax or other error - the whole script stops.

jsFiddle does not support jQuery.globalEval(), but I used eval() instead to simulate.

http://jsfiddle.net/55FfW/
Try changing var codeforeval to some wrong javascript code and next command will fail.

Is there a way to avoid other JS code from stopping in case of error and/or is there a way to check syntax before eval?

Tried using this one:

try {
jQuery.globalEval(jscode);
} catch (e) {
if (e instanceof SyntaxError) {
alert('JS error!');
}
}


Does not work for me!

Answer
            try {
                jQuery.globalEval(data.js);
            } catch(e) {
                console.log(e);
            }