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.