简体   繁体   中英

Multiple Javascript tag inclusions in jsp

Here is my code in a jsp:

<script>  
var myArray = [];
</script>
    <c:forEach var="attributes" items="FROMthisBEAN"  varStatus="vStatus" >  
                <script>
                 //Executes for each iteration. Do something COOL.
                 myArray.push("Something from this iteration");
                </script>
    </c:forEach>

Now please consider the following:

<script>  
    var myArray = [];    
        <c:forEach var="attributes" items="FROMthisBEAN"  varStatus="vStatus" >  
                    myArray.push("Something from this iteration");
        </c:forEach>
 </script>
<c:forEach var="attributes" items="FROMthisBEAN"  varStatus="vStatus" >  
                //Executes for each iteration. Do something COOL.
</c:forEach>

Both the codes give me the same output.
The question is which one is better when it comes to performance?
In the first case the script tag inside c:forEach repeats again and again.
But in the second case I'm creating one more c:forEach which is already present in the JSP.
Totally lost here. Please advise.

It's completely unnecessary to put those things in separate <script> tags. If you really want to make it better, you should possibly be thinking of creating a JavaScript array literal instead of a series of "push()" calls. A JSP extension to render a Java array as JSON would do the trick.

edit — to elaborate, a JSON encoder made available as a JSTL function would allow you to write something like:

<script>
  var myArray = ${yourTLD:toJSON( some.java.array _)};
</script>

The "toJSON" function would take the array and render it as standard JSON, depending on its contents (and of course that'd probably be somewhat constrained, depending on the JSON code used). The resulting JavaScript delivered to the browser would look something like:

<script>
  var myArray = [ "something", "something", "something" ];
</script>

again depending entirely on what's in the Java array. There are various JSON encoding libraries for Java, and it's not terribly hard to write one (and in fact that can be easier in special cases than adapting an open source library). Providing the function as a JSTL EL function is a matter of creating a public static function somewhere and declaring it in your .tld file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM