Question

myVariable = "<%=myVar%>"
if ( myVariable == "Y" )  doSomething;
else doSoemthingElse;

I'm modifying code to be compilable in Advanced Mode. Modifying Javascript using JSP/ASP/PHP/etc to inject variables is fairly common. The methods I can think of for dealing with this involve using:

global variables

myVariable = window["myVariable"];

eval

myVariable = eval('"<%=myVar%>"');

replace using pre/post-processing script,

passing as function variables

function exposedFunction(myVariable){/* stuff */}

or passing an object and accessing properties by name

It'd be great if there were some way to annotate a variable as an unknown variable, even though it is defined as a string, or to trick the compiler into thinking so.

Maybe a better approach would be to create a pre/post-processing script for embedded Javascript that handles all these things?

EDIT: It can be tedious searching out inlined variables or even worse more complicated <% %> snippets embedded in inline scripts and onclick events in html tags.

What would be the best recommended approach?
I'd like to be able to inline the <%=myVar%> string if possible, so that the output becomes

if("<%=myVar%>"=="Y")doSomething;else doSoemthingElse

But if not possible, would it be recommended to create a pre/post-build tool, just use global variables, use functions, or just treat it as situational?

Google themselves seem to inject inline variables into their inline Javascript some places. Perhaps they have a pre/post-build tool?

What are some of the main considerations I should consider when choosing an approach? I can only think of time/effort investment. Is this just a case of trying too hard to optimize; should I just extract the <%%> things and put them in global variables?

Was it helpful?

Solution

If used directly in a string <%...%>, you have to worry about whether the compiler will consider them constants:

"<%X%>" === "<%Y%>"

Will evaluated at compile time. Similiarly, "if ('<%Foo%>') ..." is equivalent to "if (true) ...", so in general it is unwise to use them the substitutions directly.

Pre-processing the code to so that they substitutions are replaced in way that is safe for the compilation, seems reasonable:

"" + eval('"<%X%>"') + ""

But is tricky if you use source maps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top