简体   繁体   中英

How to clear javascript objects retrieved from JQuery.HTML()

I have an application that having the below requirement:

The pages of the application always contains page header, main content (center), and page footer. As per user requirement, the page header & footer should remain static, whenever user navigate from one page to other, the app should only refresh the main content (center) but NOT the header & footer.

The application was initially setup by other ex-colleagues, it is not using Single Page Application, and yet we do not prefer to use iframe to achieve the above mentioned requirement. The approach we use is: use the JQuery to fetch the page from server, and then render the page into a dedicated html div, via command $(div).html();

However, now we noticed there are some potential issue with the approach that we are using. The pages retrieved from the JQuery, most of them contains javascript objects (variables, functions), which are global by default. Without refreshing / reloading the entire page, the javacript objects will remain there, which may cause unexpected behavior, more over the javascript objects will be accumulated in the page which shall impact the performance.

I have tried the JQuery.empty() method however it only clear the DOM elements but not those javascript objects.

Here is how we render the main content into the center div:

function switchPage(pageUrl) {
    $.ajax({
        url: context + pageUrl,
        cache: false,
        success: function(result) {
            $("#main-content-panel").html(result);
    }
   });
}

Please advise there is a way to clear those javascript objects effectively with minimal effort? Or if these JQuery approach is a wrong option in the first place, what could be a better approach with minimal effort of changes (as we have already built many pages, and hence we wish to minimize the changes).

TQ.

That's quite dirty, but quick resolve you can try:

If you have global JavaScript alredy loaded, only thing you have to do is cut out all javascript from incoming result by removing all "script" tags. If you need to preserve some scripts with eg. new variables, functions to replace etc. you can mark them with eg. "live-script" class:

function switchPage(pageUrl) {
    $.ajax({
        url: context + pageUrl,
        cache: false,
        success: function(result) {
          var $result = $(result).find("script:not(.live-script)").remove();
            $("#main-content-panel").html($result);
    }
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM