I am planning to load JS files using AJAX and then eval them to execute the code. But I am worried of using eval. Just to see how jQuery implements the getScript method I went through its source code and found this:
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/;
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" )
.replace( rcleanScript, "/*$0*/" ) );
globalEval is a method which evaluates the script in global (window) context and takes care or cross-browser compatibility. But I did not understand the replace part. By the name it look like rcleanScript is used to clean the script so that it is secure to execute it. But I did not understand how it works.
Can someone explain this?
EDIT: I know it is replacing some CDATA section with /$0/. But how does that make it secure? In essence how would it be insecure to execute the script without replacing the CDATA part?
That regex matches one of two different things:
These constructs are frequently used at the beginning of
scriptelements to make sure the page validates and that it renders properly in browsers that don’t support Javascript. The regex comments them out by putting them within Javascript comment blocks/* ... */. This prevents them causing errors — obviously they are not valid Javascript so they can’t be evaluated as such.In the second argument to
replace,$0represents the whole substring matched by the regular expression. So/*$0*/says “put everything matched by that regex within comments”.