What is the best way to modify and execute js and css (less) files dynamically using ajax and jQuery?

Whenever I click a button, an ajax call is triggered to load various html code into a div with the id 'main'. While displaying the html content is not an issue, integrating and applying css and js code to my current page has proven to be challenging.

I have experimented with several approaches, but none have yielded the desired results.

Initially, I attempted to pass link and script tags as strings within a json object along with my other html code, inserting them at specified locations.

$('#main').children().remove();
$('#main').append(data.html);
$('body').append(data.js);
$('head').append(data.css);

Although these elements appeared correctly when inspected under the 'sources' tab in the browser (chrome), they failed to execute/run.

Subsequently, I tried assigning id attributes to the css and js elements, then modifying their href and src attributes accordingly. This allowed me to replace the css and js related to the previous html code inserted in the div as intended.

$('#lessAjax').attr('href', 'location/style.less');
$('#jsAjax').attr('src','location/main.js');

Again, while these changes were reflected in the browser's inspection tool, the code did not execute/run, mirroring the prior issue.

An alternative approach involved utilizing the $.getScript() method for the js file, successfully executing the script enclosed within

$(document).ready(function(){....}
. However, the script was untraceable in the browser's inspection tool, impeding debugging efforts.

Additionally, I ventured to include css files using:

$('<link href="location/style.less" type="text/css" rel="stylesheet/less">')
.appendTo("head");

While this method incorporated the css file, it still did not execute/run properly.

My aim is not just to embed css and js code within script and style tags; rather, I seek the ability to interchange css and js files as the html content within the div undergoes modifications via Ajax (jQuery).

Despite numerous attempts over 5 hours, I am unable to recall every variation I explored. Is there a common solution to this dilemma? Are there any reasons why this approach might be discouraged?

Your assistance would be greatly appreciated.

Answer №1

Utilizing jqueryMobile to Load External Scripts

Is it Possible to Load External CSS Stylesheets on Demand?

It is recommended to consider utilizing a templating engine for handling content like this. There are numerous options available such as underscoreJS, along with supporting frameworks like Knockout, AngularJS, and Backbone.

$("#somebutton").click(function(){
    var path = 'path to css';
    $.ajax({
        url: path,
        type:'HEAD',
        error: function()
        {
            alert("failure")
        },
        success: function(result)
        {
            alert("success")
        }
    });
})

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

Deliver an extensive JSON reply through a Node.js Express API

When dealing with a controller in a node/express API that generates large data sets for reports, reaching sizes as big as 20Mb per request, maintaining a positive user experience becomes essential. What strategies can be employed to efficiently handle suc ...

What are the different ways I can utilize AJAX in place of an iframe?

Currently, I am utilizing iframes on my website to showcase content from other pages such as forms. However, I am facing an issue on the login page where upon user login with a form inside an iframe, the next page appears within the login iframe which is n ...

Designing a card flip animation featuring front and back faces without using absolute positioning

Looking to enhance my website with a new feature that incorporates the card-flipper schema found on David Walsh's site: https://davidwalsh.name/css-flip. The challenge arises from the fact that the content within my cards is dynamic, making the height ...

Implementing child components in React using TypeScript and passing them as props

Is it possible to append content to a parent component in React by passing it through props? For example: function MyComponent(props: IMyProps) { return ( {<props.parent>}{myStuff}{</props.parent>} } Would it be feasible to use the new compone ...

I'm curious about the specific purpose of /1 in font styling at 16px

Can anyone explain the purpose of /1 in the font: 16px/1 style declaration? I removed the /1 from the code and noticed increased spacing between lines. What is the specific role of /1 in this situation? body { font: 16px/1 'Open Sans', sans ...

Monitor the user's attendance by utilizing two separate for loops

I'm currently developing an angularjs attendance tracking system and I'm facing challenges when it comes to accurately counting the number of days an employee is absent. Despite attempting to solve this issue with two nested for loops, I am still ...

How can we use Bootstrap to ensure that items in a div are aligned horizontally on larger devices and vertically on smaller devices?

I am currently working on creating a div that contains some information, similar to the layout used on the Coinbase website. However, I am encountering issues with styling as I want this div to be responsive - horizontally aligned on larger devices and ver ...

Is there a way to retrieve JSON data for a specific category of an item?

I have some data that includes categories and items stored in JavaScript arrays: var category = [ {id:0, name : "category_1"} , {id:2, name : "category_2"}, ]; var items = [ {id:0, name : "a", category_id : 0} , {id:1, name : "b", categ ...

Facing issue with Codeigniter AJAX form where post data is not being collected

I am attempting to send a newsletter form to Codeigniter using AJAX. I have implemented CSRF protection, but I am facing issues with retrieving the posted values and receiving the response correctly. Here are the various scenarios: When I include name="e ...

Tips for utilizing flexbox to position a button to the right of an InputSelect

Struggling to position a button next to a dropdown? No matter what I attempt, the button keeps ending up above the dropdown. Ideally, I'd like it to appear alongside 'Select Organisation' as shown in the image below: https://i.sstatic.net/w ...

After a span of two minutes, the Node.js and Express server terminates the connection

I am currently working with Express 4.X and Node.js 0.12. One of the routes in my application is responsible for uploading and processing files. However, I have encountered an issue where some file uploads are taking longer than the default 2-minute timeo ...

Dynamic forms with live updates in Django

I have a vision for my website where I want to incorporate a dynamic form that can be accessed and updated by multiple users simultaneously. The idea is that as one user makes changes to the form, those updates are immediately visible to all other users wi ...

Leveraging Swift's self within Javascript for interacting with Swift class properties and methods

In a project I am working on, I use a JS method called function jsMethod(selfRef) from a Swift class. Let's say we have a class A where this method is invoked. The selfRef parameter holds a reference to the instance of class A. How can I utilize this ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

JavaScript inheritance through prototypes and the properties of objects

I am currently exploring the concept of prototyped inheritance in JavaScript for a function. This process is well documented in Wikipedia's javascript article. It functions smoothly when dealing with simple JavaScript types: function Person() { t ...

Can you explain the meaning of this AJAX code snippet?

I've been researching online for information, but I'm struggling to find any details about the AJAX code snippet that I'm using: function getEmployeeFilterOptions(){ var opts = []; $checkboxes.each(function(){ if(this.checke ...

When using HTML5 input type number with 16 or more digits, Chrome automatically replaces any extra digits with zeroes

Has anyone else encountered an issue with Chrome related to using the input type number when the number of digits exceeds 16? I've noticed that in my case, any numbers beyond the 16th digit are automatically replaced with a zero when the field loses f ...

Maintain the fixed placement of an absolute element by adjusting the browser window size

Seeking assistance here - I currently have a box that occupies the entire window. This box is designed to be responsive with a noticeable red border. Within this box, my goal is to insert tables with specific X and Y coordinates. However, my issue arises ...

Tips for passing multiple items for the onselect event in a ng-multiselect-dropdown

I've got a multi-select dropdown with a long list of options. Currently, when I choose a single item, it triggers the Onselect event and adds data from the newArrayAfterProjectFilter array to the myDataList based on certain conditions in the OnselectE ...

Determine whether the browser tab is currently active or if the user has switched to a different

Is there a way to detect when a user switches to another browser tab? This is what I currently have implemented: $(window).on("blur focus", function (e) { var prevType = $(this).data("prevType"); if (prevType != e.type) { // handle double fir ...