What are the consequences of running scripts from ajax loaded pages? - javascript

I built/manage an SPA (single-page application) interface. It doesn't use modern frameworks like VueJS or React... It uses AJAX.
It's a custom interface that loads parts of the pages through ajax. When you click an item to edit, a window on page or modal is opened and all the HTML and JS dependencies of that specific page from AJAX is injected into the page. When a new page is loaded, the existing html is replaced (I do jQuery for most of the actual functionality) with like html(new_content)
Potential Problem:
Inside these ajax loaded pages, it runs javascript, for instance, "attach to this button on click", "initiates a datatables class" for the content being loaded into tables etc. When another page is loaded, it replaces the existing content from the previous, the new page loads its own JS again.
1) Unique variables loaded from the Ajax pages still exist even after a new page is loaded from ajax. (looking the variables in the console show they exist), I am assuming loading variables with the same name get replaced with new values.
2) Functions/Classes that are being added are still embedded in the memory even after I've asked it to delete everything
Another example, if I ran a setInterval() timer, after a new page is
loaded and it replaces existing content, the setInterval is still
running.
What are your thoughts here? If the user doesn't reload the actual page by using the browser refresh, then loading these ajax pages over and over again will ultimately drain the memory of the client's device?
Is there a way to keep a clean slate after each page is loaded so existing variables loaded in memory are erased? Or do I make sure each page being loaded is wrapped into an anonymous function that is cleared after each page is loaded?

Related

jquery mobile - how to load page properly after coming back from external link

I have created JQM website where i used single page design, which means my index.html is loading first with all .js, css etc files.
My remaining pages are simple Divs with data-role="page".
When i am traversing through the website then browser URL is getting changed and back button is also working.
But the problem is :
Website contains payment system and for that, user will be redirected to payment page from my website, upon success/failure, payment page is trying to redirect back to my website's last URL which will be like:
http://<ip>:<port>/appName/pages/page-name.html
but this is not loading with any css or JS files.
Is there any way i can retain the last session?
Please help me to resolve this issue.
Thanks in advance
Within JQM you cannot directly link to a specific page within a multipage document.
The way jQuery mobile works when you link to a page with multiple pages it will default to loading the first page. You will need to use the subpages plugin to load the page with AJAX
You should either separate your pages or preload the multipage document via AJAX (with the plugin) and then link to it as an internal page
From the Documentation
Note: You cannot link to a multipage document with Ajax navigation
active because the framework will only load the first page it finds,
not the full set of internal pages. In these cases, you must link
without Ajax (see next section) for a full page refresh to prevent
potential hash collisions. There is currently a subpage plugin that
makes it possible to load in multi-page documents
It's important to note that if you are linking from a mobile page that
was loaded via Ajax to a page that contains multiple internal pages,
you need to add a rel="external" or data-ajax="false" to the link.
This tells the framework to do a full page reload to clear out the
Ajax hash in the URL. This is critical because Ajax pages use the hash
(#) to track the Ajax history, while multiple internal pages use the
hash to indicate internal pages so there will be conflicts in the hash
between these two modes.

What to use with history api instead of hash to differentiate between sections on a web page?

I have this url:
domain/?budget=0-&pn=1
Now i have a button which clicks a special view on the same page. I have done it like:
domain/?budget=0-&pn=1#special
The problem is that i am implementing history api and change in hash is causing popstate to be triggered which is not good.
What should i use instead of hash for such situation with html5 history api?
Using Single Page Applications (SPA The wiki definition is https://en.wikipedia.org/wiki/Single-page_application)
where a single page acts as the host page for other content loaded on demand into the page. In this case, the use of page templates ensures that every page, at one time or another, acts as the content host as well as a content page.
depicts how the HTML pages are structured. Each has the required structure around the page along with a content container whose inner HTML is replaced with a fragment of HTML from a content page. The identifier in the URL represents the unique identifier of the page content that is loaded into the page.
What makes use of the history object’s new members so valuable is that even though you can programmatically change the browser location without posting back to the server, at the same time that updated location is nothing more than a regular URL, which can be shared, copied or bookmarked. This means that you need to make sure your application works just as well upon the initial request of the page as it does when JavaScript is used to fetch the page.
demonstrates how Page 1 is affected by navigating to Page 2 using the history.pushState function. The overall structure of the page is preserved and after the response of an Ajax call is received, only the page fragment is injected into the content container. Notice how the page title remains the same, but the URL and content in the container reflect content from Page 2.
Consider though if you refresh the page after you navigated to Page 2 using pushState. Figure 3 shows how the page, when refreshed, keeps the correct URL and preserves the page content, but the page title reflects that it was served directly from Page 2.
This behavior is achieved by all pages having the same layout structure but include identifiers in the markup to specify the content fragment in the page. This is the same spirit in which a normal client/server web application would serve full HTML pages upon a standard GET request of the page, but then use a service in conjunction with an Ajax call to only update specific parts of the page.
Remember
As with most areas of new HTML5 capabilities, the functionality found in the new history object is available via a polyfill library that can fill in the gaps for older browsers or those that are yet to implement the standard.

How to apply JavaScript changes in Firebug?

I am playing around with a JavaScript code in Firebug and I would like changes to take effect in that page. Especially when there is code inside jQuery's $.ready() function.
Some kind of refreshing the page without losing of what has been edited. Is there any way to do that?
Page changes made via Firebug or via Javascript do not persist from one page load to another. Each time a page is loaded, the original HTML, CSS and JavaScript is parsed and loaded (from cache or from the server). Any prior changes will not be there.
The only way for a dynamic page change to be still present after a refresh is for you to save the changed state to a persistent location and then rebuilt the appropriate page content from that state each time the page is loaded.
But, if you make a change to the page and store some state in a cookie, in local storage or on your server, then you can have JavaScript that runs each time the page loads that gets that state from wherever you stored it and then applies the appropriate change to the page. If you're saving the state on the server (on behalf of this particular user), then you could even have the serve modify the page contents before it is served to the browser.
You can type JavaScript code in the Firebug command line and see changes take effect on the page. You can do the same in the Firefox, Chrome, Opera and Safari DevTools.
Changes to pages done via Firebug do not persist. After a page reload the original sources will be loaded again (from the server or the browser cache).
Currently Firebug doesn't allow you to edit the code of the loaded scripts directly.
Though you can execute JavaScript code within the context of the page by using the Command Line:
Or for longer scripts you can use the Command Editor:
But again, code you executed there will be gone as soon as the page is reloaded.
To make permanent changes to the JavaScript code of a page you need to have access to the server and make them there.

AJAX App JavaScript Loading Issue

I am creating a complete ajax application where there is one base page and any pages the user navigates to within the application are loaded via ajax into a content div on the page. On the base page I include the various scripts that are needed for every page within the application (jQuery, jQuery-UI, other custom javascript files). Then on the various pages with the application I include a script or two for each page that contains the logic needed for just that page. Each of those script files have something that executes on the page ready event. The problem is that every time the user navigates to page1, the page1.js file is loaded. So, if they visit that page 10 times, that script is then loaded ten times into their browser. Looking at the Chrome script developer tools after running around the site I see tons of duplicated scripts.
I read somewhere about checking to see if the script has already been loaded using a boolean value or storing the loaded scripts in an array. But, the problem with that is that if I see the script is already loaded and I don't load it, the page ready function doesn't get fired for the page's javascript file and everything fails.
Is there an issue having the javascript file loaded over and over when the user visit the same page multiple times?
I did notice looking at the network traffic that every time we visit the page, the script is requested with a random number parameter (/Scripts/Page1.js?_=298384892398) which causes the forced request for the script file every time. I set the cache: true settings on the jQuery ajaxSetup method and that removed the parameter from the request and thus the cached version of the javascript file was loaded instead of actually making a separate HTTP request for it. But, the problem is that I don't want all the ajax requests made to be cached as content changes all the time. Is there a way to force just javascript files to be cachced but allow all other ajax requests to be not cached.
Even when I forced caching on all requests, the javascript file still showed up multiple times in the developer tools. Maybe that isn't a big deal but it doesn't seem quite right.
Any advice on how to handle this situation?
About your first question:
Every time you load a JavaScript file, the entire content gets evaluated by the browser. It solely depends on the content if you can load and execute it multiple times in a row. I'd not consider it a best practice to do so. ;)
Still i'd recommend that you find a way to check if it was already loaded and fire the "page loaded" event manually within the already present code.
For the second question: I'd assume that the script is intended to show up multiple times when including it multiple times. To give an advice on how to not cache the loaded JS i'd need to know how you loaded the code, how you do AJAX and the general jQuery setup.
After doing some more research it looks like it is actually just a Chrome issue. When you load a script via AJAX you can include the following in your code to get it to show up in the the Chrome developer tools
//# sourceURL=some-script-name
The problem is that when you navigate away from the page, the developer tools keeps the script around, but it is actually not longer referenced by the page.

Append javascript/html to page when navigating from a different page?

Alright, first off this is not a malicious question I'm asking. I have no intentions of using any info for ill gains.
I have an application that contains an embedded browser. This browser runs within the application's process, so I can't access it via Selenium WebDriver or anything like that. I know that it's possible to dynamically append scripts and html to loaded web pages via WebDriver, because I've done it.
In the embedded browser, I don't have access to the pages that get loaded. Instead, I can create my own html/javascript pages and execute them, to manipulate the application that houses the browser. I'm having trouble manipulating the existing pages within the browser.
Is there a way to dynamically add javascript to a page when you navigate to it and have it execute right after the page loads?
Something like
page1.navigateToUrl(executeThisScriptOnLoad)
page2 then executes the passed script.
I guess it is not possible to do it without knowledge of destination site. Although you can send data to the site and then use eval() function to evaluate sent data on destination page.

Categories