Top method for generating easily readable JavaScript in Java to integrate into an HTML webpage

Currently, I am utilizing j2html to generate HTML pages through Java. When the HTML calls any JavaScript function, my approach so far has been to place the JavaScript in a separate .js file. However, it seems more practical to include functions in the main application's JavaScript file only if they are general-purpose functions used across multiple pages. Functions specifically tailored for one page should be stored elsewhere. Creating separate .js files for each page has become an administrative hassle, prompting me to consider putting them directly into the HTML near the calling code.

Although this is doable, I face readability challenges with the JavaScript code within my Java code compared to when it resides in a separate .js file.

Is there a way I can write it in a cleaner and more readable manner?

private Tag artwork()
{
  return script(rawHtml("function artwork() {\n" +
          "    \n" +
          "    select   = document.getElementById('fsArtwork');\n" +
          "    selected = select.options[select.selectedIndex].value;\n" +
          "    if(selected==0)\n" +
          "    {\n" +
          "    \tdocument.getElementById('saveArtworkFilename').disabled = true;\n" +
          "    }\n" +
          "    else\n" +
          "    {\n" +
          "    \tdocument.getElementById('saveArtworkFilename').disabled = false;\n" +
          "    }\n" +
          "}"));
}

Regarding the use of templates which have been suggested; I haven't adopted them due to several reasons:

1. My webpages are currently not designed using templates, so transitioning to a template-based system would require a significant overhaul from scratch.

2. For consistency purposes, rewriting all pages in templates would restrict my creative freedom in how I structure and design them.

In essence, the main benefits of templates such as separating responsibilities between web developers and server developers do not apply to my current situation.

Exploring Other Solutions

While attempting various solutions, I encountered an issue where the generated page could not find the external JavaScript file 'artwork.js'. The initialization was set up correctly in the code, but the location within the main classpath caused confusion.

    staticFiles.externalLocation(Platform.getPlatformReportFolder().getPath());
staticFiles.location("");

scriptWithInlineFile_min("javascript/artwork.js"),

Upon further analysis, I realized that the problem stemmed from using a relative path instead of an absolute path for the JavaScript file reference.

Resolving Deployment Issues

After correcting the file path, the solution worked smoothly in development environments. However, upon building and running outside of development mode, the file was once again not found, even though it existed within the main jar file under '/javascript' directory.

Update: Bug Fix

Finding a resolution led me to discover a bug in j2html (https://github.com/tipsy/j2html/issues/84). This bug was addressed in version 1.2.1, surpassing the version (1.2.0) I had been using. Subsequently, everything began working as intended.

Conclusion

While this method may not strictly adhere to conventional templating practices, it serves its purpose effectively for my needs. By incorporating page-specific JavaScript into a file and embedding it directly into the rendered HTML file within the main jar file, deployment concerns typically associated with standard files are mitigated.

Answer №1

My suggestion is to keep your JavaScript code in separate .js files. You can include them using either

script().withScr("/path/to/file.js")
if the file is hosted online, or
scriptWithInlineFile_min("/path/to/file.js")
if you prefer to read the file from the classpath or file system.

Answer №2

(I can barely recall my Java knowledge and I understand that StringUtils is no longer needed for joining strings.)

private Tag artwork() {
  String[] js = [
    "function artwork() {",
    "  select   = document.getElementById('fsArtwork');",
    "  selected = select.options[select.selectedIndex].value;",
    "  if (selected === 0) {",
    "    document.getElementById('saveArtworkFilename').disabled = true;",
    "  } else {",
    "    tdocument.getElementById('saveArtworkFilename').disabled = false;",
    "  }",
    "}"
  ];

  return script(rawHtml(StringUtils.join(js, "\n")));
}

However, I would still include it in a template, load the data into it, and send it to the client. The output from any well-designed template engine will eventually be similar to this code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

VueJS error: 'Property or method is not defined on the instance' message appears despite the method being defined on the instance

Is there a way in Vue.js to dynamically assign the class 'adjust' based on the value of a computed property called "isTrueSet"? I keep encountering the following error message: [Vue warn]: Property or method "itTrueSet" is not defined on the inst ...

What is the best way to display or conceal buttons when the textarea is in focus or out of focus, while still allowing them

Seeking help to include two buttons beneath the input box. One button is for saving the input in the textarea, while the other is for aborting. The buttons should only be visible when the input field is focused. An issue I am facing is that clicking on ...

Call a function within square brackets that you may not be familiar with

As a newcomer to Javascript and vue.js, I recently started using Vue to create a management system for our company. While studying codes online to learn how to use it efficiently, I came across a code fragment that puzzled me. How can I define a function i ...

Troubles with Installing CRA and NextJS via NPM (Issue: Failure to locate package "@babel/core" on npm registry)

Summary: Too Long; Didn't Read The commands below all fail with a similar error message... Couldn't find package "@babel/core" on the "npm" registry create-react-app test npm install --save next yarn add next Details of Running create-re ...

Is there a way to sequentially execute requests in a loop?

My goal is to extract a list of URLs from the request body, pass them to a request function (using the request module) to retrieve data from each URL, and then save that data to MongoDB. The response should be sent only after all requests are completed, in ...

Awaiting the outcome of the Typescript map function is non-existent

In order to find the subcategories of an article, I am utilizing a many-to-many relationship with TypeOrm that requires Ids. However, I encountered an issue where the map function is not properly waiting to push the results into the array. Below is the c ...

Testing inherit from a parent class in a unit test for Angular 2

Trying to create a unit test that checks if the method from the base class is being called This is the base class: export abstract class Animal{ protected eatFood() { console.log("EAT FOOD!") } } Here is the class under test: export ...

Discover the value of a string within an array

After spending a few hours working on a simple script, I find myself at a roadblock. The script involves an Array containing JSON values. When a user enters a search string and clicks a button, the script compares the string with the values in the Array. ...

Ways to avoid modal from appearing when users select text

In my current setup, there is a table where each row can toggle a dynamic modal form to modify the contents of the database linked to that specific row. The code in question looks like this: <tr data-toggle="modal" data-target="#Modal"></tr> ...

Creating a JFreeChart with shaded and circular nodes

After creating a line chart, I realized it doesn't look the way I want. I'm not sure what kind of chart this is supposed to be, but I would like it to have a shadow effect and circular nodes like this example: Can anyone help me achieve this des ...

sophisticated mongoose search utilizing $where clause

Dealing with a complex mongoose query has been giving me a headache. As someone who is still new to it, I was hoping for some suggestions on how to solve this issue. The gallery collection I am working with has the following fields: status (with value ...

Utilize various arrays within a single component

Incorporating react, I am faced with the challenge of passing data by props to a component that originates from two separate arrays. How can I effectively pass this data while ensuring only one component is created? If I attempt to map both arrays as is, ...

"Unlocking the Power of Promises: A Beginner's Guide to Utilizing JavaScript Prom

I recently started using Redux in my project and I encountered a scenario where I needed to make a network call after updating the store. To achieve this, I decided to use promises like so: let promise = new Promise(function(resolve, reject) { updateSt ...

Effortless Scrollspy with a custom Navigation Component, no Bootstrap needed

In my Table of Contents, identified as #TableOfContents, each href points to either an h2 or h3 tag. The issue I'm facing is that when the heading (h2 or h3) is observed by the intersection observer, the corresponding link in #TableOfContents is high ...

The link in the drop down select is not functioning in IE8/9. When trying to open the drop down select link, an

Could use some help with IE8 and 9 compatibility, can't seem to find a solution. This code works smoothly on Chrome, FF, and Safari. There are two dropdown menus, each with two links. Every dropdown menu has its own "Buy Now" button. Upon selecting ...

Unexpectedly, the child component within the modal in React Native has been resetting to its default state

In my setup, there is a parent component called LeagueSelect and a child component known as TeamSelect. LeagueSelect functions as a React Native modal that can be adjusted accordingly. An interesting observation I've made is that when I open the Lea ...

Javascript is handling the JSON Request flawlessly, however, when using Nodejs, an error is encountered with a status

I'm trying to fetch a simple JSON File in NodeJS. Using Javascript and jQuery, it functions perfectly: $(document).ready(function() { $.getJSON('https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter', function(json) { if ...

Issues with AJAX requests failing to fire with the latest version of jQuery

A small script I have checks the availability of a username in the database, displaying "taken" if it's already taken and "available" if it's not. The code below works perfectly with jQuery v1.7.2. However, I need to update it for jQuery v3.2.1. ...

`req.user` seems to be unresolved, but it is actually defined

Currently, I am working on developing an Express.js application that utilizes Passport.js for authentication in an administration panel. The program is functioning correctly at the moment, with my app.js initializing passport and setting up sessions proper ...

Exploring the seamless integration of static class members in Java and Scala

According to the book Insights into the World of Scala Programming: // Scala object DisplayOptions { def main(args: Array[String]): Unit = { System.out.println("Selected options:") for (val option <- args) if (option.sta ...