SteveC
SteveC

Reputation: 371

Is there no way to make eval() load functions?

Background: I'm trying to create an online application that runs in a single page. That page will have an element, the contents of which I will change at runtime as the user navigates through the application. I want to load stuff at runtime to avoid a large initial loading time for the application.

Problem: Loading the page elements as I go along I think I've grasped, but I can't work out how to load the JavaScript to go with each of those sets of elements as I load the elements. I thought that I'd use eval(), but there I ran into a problem — I get an error like the following: ReferenceError: testEval is not defined, so eval() doesn't seem to load the functions, which I was expecting it to. The code below reproduces the problem.

Am I missing something about how to use eval? Is there an alternative?

I'm considering creating an object in the evaluated script and then referencing it to use its functions and use bind() to set up the event handling. However, I get the impression that I may be drastically overcomplicating this (as I tend to) unnecessarily. Also it's doing my head in trying to work out how to add a function to an object created without an Object Constructor (another function, D'oh!).

Please help.

function publiListElementLoad(result) {
    testEval();
}

function publiListScriptLoad() {
    eval("function testEval(){}");
}

publiListScriptLoad();
publiListElementLoad(result);

Upvotes: 0

Views: 80

Answers (2)

Ricki Runge
Ricki Runge

Reputation: 421

eval will set this in the current scope, which is the function publiListScriptLoad, and you expect it to be declared in the global scope.

To come around this you may do it by putting adding your function to window object

Working version: http://jsfiddle.net/y50xtf31/

function publiListElementLoad(result) {
    testEval();
}

function publiListScriptLoad() {
    eval("window.testEval = function() { alert('Hello World');}");
}

publiListScriptLoad();
publiListElementLoad("");

But be careful with eval-function - it is a over-powerful function and should be used with great care.

Upvotes: 0

joeltine
joeltine

Reputation: 1630

You can dynamically create script tags to fetch the extra JS as you need it:

   var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= 'somefile.js';
   head.appendChild(script);

Upvotes: 1

Related Questions