I have a dynamic website where all links grab new sections via an ajax request from other pages and replace the current section.
My problem comes in two forms. When I load a new div from an Ajax get request. Some sections need js files too. For example, one uses a particles.js as a canvas background. After I complete the ajax request I then getScript"js file" and it works. However if you move onto other sections that getScript is still running and now unbinded because that section is gone. If I go back to that section again I need to getScript again and now I'm running it twice. This can be very CPU and GPU intensive and slows down my site.
Things like css files are easy because I can create an if statement to load if its not already loaded, script tags are different because the Dom only loads once. Appending/removing the script to the head is useless because the site is entirely Ajaxed.
here is example of a script
//pricing.html
$(".link-pricing").click(function (e) {
e.preventDefault();
$("#togglenav").collapse("hide");
$("#main").load("../../damonmedek/home/pricing.html #main-pricing");
$(document).ajaxComplete(function (event, xhr, settings) {
if (settings.url === "../../damonmedek/home/pricing.html") {
//Add CSS
if (!$("link[href='../assets/css/home%20css/pricing%20css/particles-js.css']").length)
$('<link href="../assets/css/home%20css/pricing%20css/particles-js.css" rel="stylesheet">').appendTo("head");
//Remove CSS
$('link[rel=stylesheet][href*="../assets/css/home%20css/best-carousel-slide.css"]').remove();
//Add JS
$.getScript("../assets/js/home/pricing%20js/modal%20popup.js", function () {});
**$.getScript("../assets/js/home/pricing%20js/particles.js", function () {});**
$.getScript("../assets/js/home/pricing%20js/pricing-animated%20heading.js", function () {});
$.getScript("../assets/js/members%20js/ajax%20members-only.js", function () {});
$.getScript("../assets/js/home/pricing%20js/app.js", function () {});
$.getScript("../assets/js/members%20js/ajax%20members-only.js", function () {});
}
});
});
How can I rebind page to js file, or stop getScript, or some smarter way to fix this problem? Its not just cpu problems, duplicate getScripts can cause problems like posting twice on submit and weird stuff like that.