Using AJAX only for whole website,optimal or not - javascript

I am having a template structure in which there is a single HTML file inside which related HTML & JS files are loaded (using AJAX).
Section are loaded as per User's activity(Page never reloads which kind of is good for user experience).
i.e.
User clicks a menu say "Profile",which causes:
jQuery.load method is used to load a file "/some/path/profile.html".
jQuery.getScript is used in .load() callback to include js files like "some/path/profile.js",The profile js has event handlers for the profile page along with related business logic.
This happens for each menu item/section of the application like "Profile","Files","Dashboard" etc.
It works fast but I am not sure if this is the optimal way to carry this out.
If a User consequently clicks the "Profile" button twice,would the browser
clear up the earlier loaded resources(profile.html,profile.js) first before
loading it afresh?
When user visit a new section say "Dashboard" after visiting "Profile",would
browser again clear out the resources of Profile before loading for
Dashboard?
If not than could this cause some memory related issues with the browser?I searched about this but did not see any related scenarios.
P.S: In this structure often some HTML part is stored in a JS variable to be used further. I read somewhere in SO that it is a bad practice to do so but I was not able to find details regarding it. I assume it should not be a -ve point if the developer is well versed & storing HTML in a JS variable should not be any problem.

Here's my understanding on this:
You have to make sure that you don't send request if clicking on same button at your end.
(Forgot about we are dealing with scripts/HTMl) No caching in the picture
Clearing out resources?, yes it will be removed from DOM if appened in same section. But i guess it's necessary if same placeholder is used for each section content.
If you know that everytime each section will return same template again, you can create a local cache at client side just like memoization to see if template already exists.
Hope this helps.

Related

Page Specific JavaScript using Content Security Policy (CSP) [duplicate]

This question already has answers here:
Best way to execute js only on specific page
(5 answers)
Closed 5 years ago.
I want to use Content Security Policy (CSP) across my entire site. This requires all JavaScript to be in separate files. I have shared JavaScript used by all pages but there is also page specific JavaScript that I only want to run for a specific page. What is the best way to handle page specific JavaScript for best performance?
Two ways I can think of to workaround this problem is to use page specific JavaScript bundles or a single JavaScript bundle with switch statement to execute page specific content.
there is lots of ways to execute page specific javascript
Option 1 (check via class)
Set a class to body tag
<body class="PageClass">
and then check via jQuery
$(function(){
if($('body').hasClass('PageClass')){
//your code
}
});
Option 2 (check via switch case)
var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname
switch (windowLoc) {
case "/info.php":
//code here
break;
case "/alert.php":
//code here
break;
}
Option 3 Checking via function
make all the page specific script in the function
function homepage() {
alert('homepage code executed');
}
and then run function on specific page
homepage();
Sorry, I know this ended up being a long read, but it'll be worth it to do it as you'll be able to make the choice that's right for your site. For a tl;dr, read the first sentence of each paragraph.
First of all, no matter which route you choose you should put all of the JS common to each page in the same file to take maximum advantage of caching. That's just common sense. Also, in all cases, I assume you're using a competent minifier since that will make a bigger difference than anything else. Packagers also exist if you need one of those -- Google is your friend if you need either of these.
For the page specific JS, you should decide whether it's most important to have your first page load (the user's first contact with your site) be 'fast', or if it's most important to have the following page loads (the user's first contact with any given page) be 'fast'. Modern browser caching is quite good now, so you can rely on the browser loading from cache whenever it can. In general, if it's most important for the first page load to be fast, then create separate JS files (this way, the user isn't stuck downloading 10 MB of data before they even get to your site). If not, then put all the JS in the same file, keeping in mind that if one page has significantly more JS than others, it will adversely affect the load time of every page on your site. Note that this extra load time can be mitigated with the use of async or defer tags, more on that later.
Consider the case where page A has 5 KB of JS and page B has 5 MB of JS. If you put both scripts in the same file, page A will load more slowly (since it needs to load ~5 MB of JS) but page B will load much faster due to the JS file being cached already. If you keep them separate, page A will load much faster than page B, but there will be an average speed decrease compared to the first case. If one page doesn't have significantly more JS than another, use separate files. You'll encounter much better average load time since the "savings" of loading the big file ahead of time will be greatly diminished (you'll also avoid the issue mentioned below).
Another consideration is whether one of the JS files will change often, as this will invalidate the cached version and require the browser to redownload it. If you put all your JS together and only one of the files is volatile (especially if it's a page not often visited, such as a registration page), the end user will face a higher average load time than if you keep them separate. Stack Overflow themselves took an interesting approach to this. It appears they have a function to invalidate the cache of JS unrelated to the page and load it (if necessary) when the JS on the page loads from the cache to save loading time later.
One more thing! Beyond all this, you should also decide whether or not you should use async or defer in your script tags since you're migrating to fully "external" JS.
async allows the page to load and display to the user before the JS is finished downloading. This is a great way to hide the download of a big JS file if you decide to go the "one file to rule them all" route. However, you might also find the JS needs to be downloaded and execute in order for the page to display properly (as is the case when not using async or defer).
As a result, it might be a good idea to use a hybrid of the two suggestions and split your js into individual files that need to be loaded per page for the page to display correctly (one per page), and put all the js that doesn't into a script that loads through an async or defer tag (this being the "one big file"). defer lets the browser load it in the background after the page is displayed to the user.
Ultimately, only you can make the decisions that are right for your app. There's no one magic option that will work in all cases, but that's the reality of software design/engineering. I hope I've made the process clearer for you so you can arrive at the right choice more easily, though.

Website design strategy: Change content or load different HTMLs

So this is kind of my first attempt at web design per se so it might be a newbie-ish question. Just to give a little background... I'm using the all time classic HTML + JS + CSS combo and Yii (PHP) as a backend with a MySQL database. I can't really tell what the site is about but the user will definitely interact with the backend and run some queries on the DB and stuff.
Right now my website is composed of 5 HTML files, each one of them has a common layout:
Header or menu with logo and user info
"Sub-Header" with a general info image and maybe some specific stuff
Content specific to that HTML file
Footer
Right now I find kinda annoying that each time I redirect the user to a different place of my site I have to check again if he's logged in, I make some use of cookies for that too, etc, etc.
I was thinking of moving my site to be a single page or template if you will and just append the (body)content of each of those files to the body of my master-page. That sounds pretty good at first thought, but are there any downsides to this or is this just how things should be done?
I've done web applications before using frameworks like Sencha and stuff and they all seem to work this way, but is this the way to go for this particular case?
EDIT
Also, what is the correct way to implement the single-page scenario?
Get all the code in one HTML file and hide the stuff I don't want to show
Remove from the view the stuff I want to hide and append the new stuff from some other HTML file.
I'm not sure I understand your situation exactly. But I think I would make another PHP file in a protected area with a function like is_logged_in() or even redirect_if_not_logged_in(). Then you can include (or require) that PHP file in the other ones and just call the function.
You definitely don't want to be rewriting the same code over and over again.

Save changes made to "contentEditable" sections back to original HTML file

How could I save changes made to "contentEditable" sections back to original HTML file. Is this even possible?
I need to create a single html file that has sections for user changes. Using their web browser, I would like the user to be able to "save" the changes so that the original HTML file would actually be updated. This file might be stored on the user's PC, it might end up hosted on a server. Wherever it is, it needs to write the changes back to the HTML file.
EDIT:
Maybe some more details will help. I am looking to create a dynamic character sheet for all the RPGs I GM. I have used doc sharing services, but the interactive and dynamic nature of HTML+javascript offer more of what I need. Designing the file is easy enough. I just want players to open it in a web browser (even if stored on their desktop), make notes and edits, and then click a "save your character" button that will write the elements they changed back to the original HTML file. If there's no conceivable way to do this, that ok, I would just like some definitive info.
The file lives on a server somewhere, and the browser retrieves the files from that server, after which you can mess with contentEditable content, so to get the changes propagated to the original files, you'll need at least two things:
an event handler on the element(s) that have the contentEditable property, so that you can hook into their content modifications.
an API on the server that lets you tell it to update file X with content Y
The basic approach would be:
load HTML from server in browser
click on element with contentEditable property and start editing
finish editing, and have the element's javascript handler kick in (see https://stackoverflow.com/a/14043919/740553 for how to do that).
take the current URL, and the route to the element you just changed, and its new content, and then POST that to the server. This requires that:
the server is running an accepting route that listens for POST data on some route like ..../changepage (without accepting input from just anyone, of course), and that:
can take a POSTed filename, element path, and content string, opens up that file, finds the element in question, replaces its content, and packs it back up into a new file with the same filename as before.
This is, to say the least, extremely fragile and prone to bugs as well as abuse. There are better ways to do this, and pretty much all of them rely on having a content server, and a page that loads in content for very specifically editable elements from your content server, so that showing, editing, and saving content all happens to "one thing" instead of to elements that need to resolved in .html files based on their element path.
Or, making things even easier, using something like React to make most of that virtually instant. Although, of course, you'll still be left with writing your server such that it can serve up content, and accept modification requests.
Unfortunately for you, what you want to do is actually extremely hard to do well, as well as securely.

Caching URL view/state with parameters

I'm making a mobile app using Cordova and AngularJS. Currently I have installed ui-router for routing but I'm open to any other alternative for routing.
My desire: I want to cache certain views bound with parameters. In other words I want to cache paths (or pages).
Example situation: let's say that we see some dashboard page, click on some book cover which redirects to the path book/2. This path is being loaded for the first time into app. Router redirects from HomeController to BooksController (whatever the name). Now the BooksController loads data for given $stateParams (book id = 2) and creates view filled with info about chosen book.
What I want in this situation:
I go back to the dashboard page - it is already loaded (cached?)
I choose book #2 again
Controller or router notices that data about this book is already loaded
The view isn't being recreated, instead it's being fetched from cache
Actually, it would be best to cache everything what I visit based on path. Preloading would be cool too.
Reason: performance. When I open some list of books then I want it to show fast. When view is being created every time, then animation of page change looks awful (it's not smooth).
Any help would be appreciated.
EDIT:
First of all, since I believe it's a common problem for many mobile HTML app programmers, I'd like to precise some information:
I'm not looking for hacks but a clear solution if possible.
Data in the views uses AngularJS, so YES, there are things like ng-bind, ng-repeat and so on.
Caching is needed for both data and DOM elements. As far as I know, browser's layout operation is not as expensive as recreating whole DOM tree. And repaint is not what we can omit.
Having separate controllers is a natural thing. Since I could leave without it I cannot imagine how it would work anyway.
I've got some semi-solutions but I'm gonna be strict about my desire.
Solution 1.
Put all views into one file (I may do it using gulp builder) and use ng-show. That's the simplest solution and I don't believe that anyone knowing AngularJS would not think about it.
A nice trick (from #DmitriZaitsev) is to create a helper function to show/hide element based on current location path.
Advantages:
It's easy.
KIND OF preload feature.
Disadvantages:
all views have to be in a single file. Don't ask why it's not convenient.
Since it's all about mobile devices, sometimes I'd like to "clear" memory. The only way I can think of is to remove those children from DOM. Dirty but ok.
I cannot easily cache /book/2 and /book/3 at the same time. I would have to dynamically create DOM children on top of some templates for each view bound with parameters.
Solution 2.
Use Sticky States AND Future States from ui-router-extras which is awesome.
Advantages:
Separated views.
Very clear usage, very simple since it's just a plugin for ui-router.
Can create dynamic substates. So it would be possible to cache book1, book2 but I'm not sure about book/1 and book/2
Disadvantages:
Again, I'm not sure but I didn't found an example with caching a pair/tuple (view, parameters). Other than that it looks cool.
This is precisely the problem I had to solve for my site 33hotels.com. You can check it and play with the tabs "Filter" and "Filter List" (corresponding to different Routes), and see that the View is updated instantly without any delay!
How did I do it? The idea is surprisingly simple - get rid of the Router!
Why? Because the way the Router works is it re-compiles the View upon every single Route change. Yes, Angular does cache the Template but not the compiled View populated with data. Even if data do not change! As the result, when I used the Router in the past, the switch always felt sluggish and non-reactive. Every time I could notice annoying delay, it was a fraction of second but still noticeable.
Now the solution I used? Don't re-compile your Views! Keep them inside your DOM at all times! Then use ng-hide/ng-show to hide/show them depending on the routes:
<div ng-show="routeIs('/dashboard')">
<-- Your template for Dashboard -->
</div>
<div ng-show="routeIs('/book')">
<-- Your template for Book -->
</div>
Then create a function routeIs(string) inside your Controller to test if $location.path() matches string, or begins with string as I am using it. That way I still get my View for all pathes like /book/2. Here is the function I am using:
$scope.routeBegins = function () {
return _.some(arguments, function (string) {
return 0 === $location.path().indexOf(string);
});
};
So no need to be smart with caching - just keep it in the DOM. It will cache your Views for you!
And the best part is - whenever your data is changed, Angular will instantly update all the Views inside your DOM, even the hidden ones!
Why is this awesome? Because, as user, I don't have to wait for all the parsing and compiling at the moment I want to see the result. I want to click the tab and see my results immediately! Why should the site wait for me to click it and then begin all the re-compiling as I am waiting? Especially when this could be easily done before, during the time my computer is idle.
Is there any downside? The only real one I can think of is loading memory with more DOM elements. However, this actual byte size of my views is negligible, comparing e.g. with all JS, CSS and images.
Another possible but avoidable downside is the re-compilation cost of the hidden views. This is where you can get smart and avoid computation-heavy parts depending on the current routes.
Also, you are not re-compiling the whole View, just the parts affected by data changes, which also lowers computational cost.
I find it quite remarkable that everyone is using Routes and seems to be completely unaware (or ignorant) of this problem.
1) About static pages in the app (views), angular takes care of loading them.
for example: for your dashboard page you need not worry about caching the page, as angular will take care of it. Angular will only load the dashboard view once and on all next requests for the dashboard view, angular will just show you the view(not load the file for view), if it is all a static view without any data loaded by ajax calls.
2) if your dashboard is itself loading the book list(or similar data) via ajax, then you can tell your controller to only load the data once and store it to localstorage and on subsequent requests to the dashboard page can only load the data from the localStorage.
3) similar approach can be used when your BooksController loads the data into a view. You can check in your BooksController if the request for a particular book is been previously made and if not your can store it to localstorage or database. and if the data was previously requested then you can load the same data from the storage without making a request to server.
Example situation:
say user makes request for book1, then
your controller i.e BooksController check whether the same data was requested before,
if not, you can load the data via the ajax call from server and also save it to local storage.
if it was loaded before you will load the data stored in the localstorage or in the database.
If you're using ui.router, then you should take a look at ui.router extras, specifically the sticky states module. This allows you to cache the state 'tree' (including rendered views) so they don't have to be compiled or re-rendered on state changes.
http://christopherthielen.github.io/ui-router-extras/
Here's a demo:
http://christopherthielen.github.io/ui-router-extras/example/sticky/#/

Animated infinite scrolling via AJAX: returning JSON or HTML?

I'm trying to create an infinite scrolling page - somewhat similar to tumblr archive pages like this. I understand the concept that I have to load the content with a server call, but I don't know how to achieve this "animated loading" design like in Tumblr.
I don't want to know the exact code, only the overall concept of the solution. So what would be the best practice to do things like this?
What should I get from the server: a bunch of JSON data or a full HTML page?
I have tried to decode the Tumblr page above, and I saw on my network traffic page that in every scroll event there is a POST request which returns a full HTML page which has its own JavaScript and CSS content!
I guess that the animation logic is inside of this JavaScript content.
But I have 2 questions about this method:
When I get the full HTML page from the server (which contains the new page as well), how can I throw the currently displayed HTML document away and I set the new one?
Isn't it too bad from a performance point of view to return a full HTML document every time? Because the full document would contain the results of the previous "pages" of the archive as well. Or do I think wrong?
Wouldn't it be better to return a JSON-only result from the server? (It have to be parsed on the client but it would be more network traffic-friendly, I guess)
If it would be better to return a JSON, why the Tumblr works on the other way?
It surely is beneficial to not send lots of data that will not be used.
However, if your server has a lot of resources, you can do some preprocessing on the server instead of client. This means, instead of JSON, you can send an HTML snippet, the block that will be added. Moreover, if your HTML structure is very complex, you don't want to implement it twice; once in HTML and once in Javascript.
The way Tumblr works might be because they don't want to add much more to the server code base, and instead offload the work to the client. Since only one page is sent at a time, the overhead is constant w.r.t. the number of pages. The client can just take the full HTML, find the corresponding element with DOM manipulation and place it somewhere.
In fact, that is what the AutoPager plugin does: It learns the "next" link and the page body from the user, then fetches additional full pages from the unsuspecting server and inserts their content into the page (and reads the next page url).
In short:
The benefit of JSON is low bandwidth usage.
The benefit of HTML snippets is low demands on client processing power, and little to no code duplication.
The benefit of full HTML is that the server needs not care if it's serving the first page or any other.

Categories