Incorporating an external JavaScript or CSS file into a Java web application at runtime

I am looking to dynamically add an external JavaScript or CSS file in my test.html file. Although I am aware of a trick that involves using jQuery like this:

 $(”).appendTo(‘head’).attr({
 rel: ‘stylesheet’,
 type: ‘text/css’,
 href: ‘**htttp://192.168.30.229:8080/**javascripts/jwysiwyg/jquery.wysiwyg.css’
});

My goal is to store the URL (http://192.168.30.229:8080/) of the CSS and JavaScript files in an XML file, such as web.xml. Then, I aim to retrieve the URL from the web.xml file and dynamically append it to the href attribute. This way, if the URL needs to be changed, for example, to **:http://192.168.100.229:7071/, the code in the HTML file does not need to be altered.

How can I properly write and read the URL from the XML file and utilize it in the test.html file?

Answer №1

  1. Incorporating external JavaScript or CSS into your HTML page can be achieved by utilizing JavaScript. Learn more about this by visiting:

  2. If you are looking to dynamically generate HTML to manipulate a specific section, JSP (JavaServer Pages) can be helpful. To do this, define a <context-param> in your web.xml and then reference it in the JSP page:

    <context-param>
      <param-name>someUrl</param-name>
      <param-value>http://192.168.1.1:8080/something</param-value>
    </context-param>
    

Next, you can reference the defined param in your JSP page like so:

<%= getServletContext().getInitParamter("someUrl") %>  

Answer №2

function deleteFile(fileName, type){
    var elementType = (type=="js")? "script" : (type=="css")? "link" : "none"; 
    var attributeType = (type=="js")? "src" : (type=="css")? "href" : "none"; 
    var allElements = document.getElementsByTagName(elementType);
    for (var i = allElements.length; i >= 0; i--){ 
        if (allElements[i] && allElements[i].getAttribute(attributeType) != null && allElements[i].getAttribute(attributeType).indexOf(fileName) != -1){
            allElements[i].parentNode.removeChild(allElements[i]); 
        }
    }
}

deleteFile("somescript.js", "js"); 
deleteFile("somestyle.css", "css"); 

The function creates a list of elements based on the file type specified to be deleted. It then loops through these elements backwards, checking if they match the file name to be removed. Removing elements in reverse order helps maintain the integrity of the loop when elements are deleted. To delete an element, the function uses the parentNode.removeChild() method.

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

I'm wondering if anyone has any insights as to why the CSS rule `body{ overflow: auto;}` is not functioning properly for me. Despite my attempts of adding a class to the body tag and

I am facing an issue where adding body tags to my code in Visual Studio code does not yield the desired results. Interestingly, it doesn't seem to be a syntax error in CSS. body{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI&apo ...

Getting a blank request body error while receiving data from an Angular 4 application in Express

My express route is indicating that the body of the request being sent is empty, according to req.body. The main node file looks like this - var express = require('express'); var bluebird = require('bluebird') const bodyParser = requ ...

Creating space between flex items in Slick Carousel with Vue

This is my current Slick Carousel. There are 4 items in a row, and I am looking to insert some margin between each item while maintaining the existing aspect-ratio: 1.3/1; I'm struggling with overriding the classes from vue-slick-carousel. Does any ...

When transitioning an iOS Swift app to the background, a NodeJS error arises: 'Headers cannot be set after they have been sent to the client'

My app is built using Swift/SwiftUI. I utilize the ObservableObject and JSONDecoder to retrieve data from my Node.JS Express API and display it within the app: struct DevicesList: Decodable { var data: [DeviceInfo] } struct DeviceInfo: Decodable { ...

Maintain and refresh the chosen option in the dropdown menu

Currently, I am working on designing a form that has a dropdown menu. My goal is to save the option that the user selects upon submission, so that when they return to the page in the future, their selected option remains as the default. I envision somethi ...

Utilizing jQuery taggd to add annotations to images

I am currently utilizing the taggd Plugin to develop an application that creates a tag whenever any part of the body is clicked. I have successfully implemented most aspects of it, but I am facing an issue with the coordinates. The tags are sometimes creat ...

The pagination feature in DataTable does not retain the edited page after making changes

I have been encountering an issue while using DataTable serverside processing. My datatable includes an edit column, and when the edit link is clicked, a jQuery dialog box appears. After submitting the dialog box, an ajax.reload call is made. However, the ...

Preventing Javascript array elements from being overwritten: Best practices

My challenge lies with the addToClients() function, which is designed to add a new value to the clients array whenever a button is pressed. The issue I am facing is that each time I press submit, the previous element in the array gets replaced by the new o ...

Setting a default value for Autocomplete in MaterialUI and React.js

Is there a way to set a default value for an Autocomplete TextField component from Material UI in React.js? I want to load a pre-populated value from the user's profile that can then be changed by selecting another option from a list. Check out my co ...

Creating an anchor element with text and a bootstrap icon involves using the appropriate HTML structure and

I am trying to figure out how to create an element that includes both text and a Bootstrap icon. Here is the HTML code: <a> Edit <i class="icon-pencil" /> </a> Can anyone help me understand how to select this DOM element using jQuer ...

Utilizing TypeScript Class Inheritance: The Reference to 'super' is Only Allowed in Members of Derived Classes or Object Literal Expressions

We have encountered a scoping issue while using TypeScript classes with inheritance. It seems that TypeScript/JavaScript does not allow us to use 'super' within a promise structure or an enclosed function. The error message we are getting is: Ty ...

Integrate HTML code from one file into another HTML file

I have a specific task in mind: I want to incorporate a header and footer from an external HTML file into another HTML file. Although there are numerous code snippets available here, I'm facing some challenges: Issue: I am unable to modify the exte ...

Wordpress is experiencing a recurring issue with scripts being loaded multiple times

Currently, I am attempting to load some of my scripts from CDNs such as CDNjs and Google. While the scripts are loading correctly, I have noticed a strange issue where each script seems to generate two or even three HTTP requests (for the same script). You ...

Standardizing URLs with ExpressJS router

Seeking normalized/canonical URLs for a single page application running on an ExpressJS server. While the SPA is supported by a server-side router, templates can vary slightly for different app URLs. One particular difference is the presence of the <li ...

The function assigned to [variable].onclick is not being executed, despite no errors being displayed in the console

I'm new to javascript and I'm looking for help with a simple task. I want to create a code that when clicking on an image, it will open in a modal. This feature is important for viewing full-size images on my portfolio. Although there are no erro ...

What could be causing my input box to act strangely when users attempt to input information?

I seem to be facing an unusual issue with the <input onChange={this.handleArticleId} value={this.props.articleIdValue} placeholder="article id"/> field. Whenever I try typing something, the letter only appears in the input box after clicking on the s ...

Issue: [$injector:unpr] Provider not found: RequestsServiceProvider <- RequestsServiceFor more information on this error, please visit the website: http://errors.angularjs.org

Despite defining my service name in all necessary places, I am still encountering the error mentioned above. Below is my app.js: var app = angular.module('ionicApp', [ 'ionic', 'ngCordova', 'checklist-model' ]) ...

An issue has occurred where an element is not interactable in Selenium Java due to it not being currently visible and unable to be manipulated

Having trouble selecting the Code 128 (standard) from the dropdown menu, despite multiple attempts. WebDriver driver = Driver.get(); driver.manage().window().setPosition(new Point(-1000, 0)); driver.manage().window().maximize(); driver.manage().timeouts( ...

CSS: Ensuring the width is adjusted to the content or wrapper that is wider

I am facing an issue with mouse-over highlighting on a set of list items. Below is the HTML structure I am working with: <div id="wrapper"> <div id="box"> <div class="item">Lorem ipsum dolor sit amet, sit nonumy utamur ponderum ex& ...

Is there a way to prevent elements on a web page from shifting when the page width becomes narrow enough?

Currently, as I delve into the world of web development with Svelte, I am in the process of creating a basic website to put my knowledge to the test. The main aim is to ensure that no matter how much the page is resized, the text and video content remain e ...