Jquery/Javascript: How to Remove JS file for a page which is not being used in current page

2.6k views Asked by At

Basically I have 4 views in my page (4 different sections in a single HTML page), I am hiding and showing the required views based on the button click.

I have 4 separate JS file for these 4 views. Based on the page user is in I am loading the JS page using the command

    //Page1
    if (current_page == 'Page1') {
        $.getScript("/js/Page1.js");
    }

I want to remove the all unused JS (JS which are used for other pages) when user navigates to 2nd page and only Page2.js should be loaded, Currently when user navigates to 2nd page (Page1 to Page2) both Page1.js and Page2.js are being loaded.

$.getScript can load the JS but is there a command or way to remove the JS from page and load the JS file dynamically?

2

There are 2 answers

0
AudioBubble On BEST ANSWER

Thanks for the response, I was able to figure out the issue and some workaround for that. Basically I had some common functions in Page1 JS and Page2 JS so I wanted some of the functions in my Page2 JS not to run when I am using Page1 but they were getting executed because of them were using same modal and form submit IDs.

I declared a variable in the JS and Based on that I made sure the functions in Page2 JS not running when I am in Page1

    var Page_Checker = "";
    //Page1
    if (current_page == 'Page1') {
        $.getScript("/js/Page1.js");
        Page_Checker = "THIS_IS_PAGE1"
    }

Use the Page_Checker and make sure the functions are not running in other JS files. May be you can do something like this in other JS files:

if(Page_Checker != "THIS_IS_PAGE1")
    return;
1
Jack Bashford On

Here's a good post that explains it, but hat you can do is remove the <script> element you are not using:

<script id="page1script" src="/js/Page1.js"></script>

And in jQuery:

if (current_page != 'Page1') {
    $("#page1script").html().remove();
}