Using JavaScript within a JSP tag

Pablo Cabrera picture Pablo Cabrera · Oct 23, 2008 · Viewed 36.9k times · Source

I've seen this question regading the importing of js-files related to the tag content itself. I have a similar problem, here I have a jsp tag that generates some HTML and has a generic js-implementation that handles the behavior of this HTML. Furthermore I need to write some initialization statements, so I can use it afterwards through JavaScript. To be possible to use this "handler" within my JavaScript, it should be somehow accessible.

The question is... Is it Ok to write inline <script> tags along with my HTML for instantiation and initialization purposes (personally I don't think its very elegant)? And about being accessible to the JS world, should I leave a global var referencing my handler object (not very elegant aswell I think), are there better ways to do it?

Answer

Magnar picture Magnar · Oct 23, 2008

You should strive for javascript in its own files. This is usually done with Progressive Enhancement. But some times you don't have a choice, for instance when the same JSP renders pages in different languages. Here's a real-life example:

The JSP:

  <script src="/javascript/article_admin.js"></script>  
  <script type="text/javascript">  
      NP_ArticleAdmin.initialize({  
            text: {  
              please_confirm_deletion_of: '<i18n:output text="please.confirm.deletion.of"/>',  
              this_cannot_be_undone: '<i18n:output text="this.cannot.be.undone"/>'  
            }  
      });  
  </script>  

The javascript (article_admin.js):

 /*global NP_ArticleAdmin, jQuery, confirm */  
 NP_ArticleAdmin = function ($) {  
     var text;  

     function delete_article(event) {  
         var article = $(this).parents("li.article"),  
         id = article.attr("id"),  
         name = article.find("h3.name").html();  
         if (confirm(text.please_confirm_deletion_of + name + text.this_cannot_be_undone)) {  
             $.post("/admin/delete_article", {id: id});  
             article.fadeOut();  
         }  
         event.preventDefault();  
         return false;  
     }  

     function initialize(data) {  
         text = data.text;  
         $("#articles a.delete").click(delete_article);  
     }  

     return {initialize: initialize};  
 }(jQuery);

In this example, the only javascript in the JSP-file is the part that needs to be there. The core functionality is separated in its own js-file.