I have a situation in which I have to use eval in Javascript. Yes, I know it is evil, but in this case it is required, because two requisites:
- The Javascript code is big.
- It has to be evaluated (and downloaded) only in a few situations, so I don’t want the script to be downloaded always, but on demand.
With these requisites, I have written an XMLHttpRequest to request the code (600+K), and I want to eval that code to take place immediately. As I’ll show later, the script contains just data to be inserted in two variables. The problem is that evaluating this javascript fails always with syntax error. If I put the code verbatim (without eval), the code executes fine. This is the minimal example. I have a search.js file like this:
// search.js for functional mind. Generated statically
// from the set of posts.
posts = { 'postlist' : ['<a href="XXX">YYY</a>', 'other link...' ] };
posts_for_word = { 'word1' : [0,1], 'word2' : [Z,K] };
The last variable, posts_for_word includes indexes of posts containing that word. The problem comes when I evaluate that Javascript inside eval:
// global environment
var posts = {}; // Initial value, empty
var posts_for_word = {}; // same
function() {
var request = // create XMLHTTPREQUEST request
var response = // obtain response (the javascript)
eval( response ); // <- syntax error
// access posts or posts_for_word
posts.postlist[ posts_for_word['word1'][0] ]
....
}
The problems:
- When I evaluate the javascript shown above with eval, firefox tells me that it is bad formed in the first line.
- I then removed the comments. I supposed that eval would evaluate it as if it was a normal Javascript program, but it doesn’t seem to accept comments (why?).
- After removing the comments, the code works, but still the Javascript console of Firefox tells me that there is a syntax error in the first line (that defining the JSON first variable). Why?
You shouldn’t use AJAX and
eval()to make a script happen on your website, instead, create a<script>element with a link to the file and append it to the body:(This code is actually taken directly from a bookmarklet of mine, and it does the trick nicely.)
As for the variable scope, if you declare them as
var variablein your inner file, it would override the file scope and become global.However, should you require a synchronous load of a script, you will have to (despite the fact it is considered bad practice) to use a synchronous AJAX call. How to do that was already written before me, Dynamically loading JavaScript synchronously