Page Renders before data pull is complete - javascript

I have two columns.
The column on the left renders first (obviously). The column on the right is injected code that is built from a data pull. The column on the right finishes rendering the page before the data is loaded and visible. Therefore the right column is blank, unless I refresh the page several times.
Is there a way to slow down the page rendering? The page renders properly in ie, but not ff and chrome.

I doubt you actually want to slow down the page render since that will annoy you users. What you probably want to do is improve your code so that it properly replaces the content of the div (or whatever) that holds your right column. Use an library like jQuery to make the request for the content as an AJAX call. Without code examples I can't give you anything more specific.

No but you can delay rendering the right column until your ajax call are completed. Depending on the Javascript library you're using, or if you're using raw Javascript, there should be a way to register a callback function to be called back when the data finished downloading from the server.
Load your data in this callback instead of relying on delaying for a specific amount of time, because that will always be wrong, too slow for some users and too fast for other users.

Related

Effectively and repeatedly updating DOM with data without breaking page

I'm creating a SPA which of course uses AJAX to dynamically load pages in a div. My layout is a side accordion menu where when you click on an item, it loads information on a div next to it. My problem is that if a person decides to click menu items as fast as they can per second, I start getting blank content in my pages. So my question is, what are some best practices (if any) to avoid pages breaking when you have people clicking so fast?
Things I'm doing for performance:
Using html templates and json files to build pages before application starts, keeping the (simple) pages in memory to grab - instead of calling ajax every click
For now, on each click I'm using at clearTimeout and setTimeout set to some milliseconds to slow down the process of switching pages - not ideal
Unfortunately, I can't post code because it's too long, but I'm hoping I can get some help with this information.
Thanks guys!
**Note: This is only front-end work, no databases because the load isn't heavy.
EDIT:
Here is a little snippet of my setTimeout and clearTimeout:
if (clickTimeout) { clearTimeout(clickTimeout); }
clickTimeout = setTimeout(function()
{
clickLink(menuItem.attr('href'));
}, 500);
I usually just disable the UI element that caused the event before sending the ajax, and then the client side code re-enables it after the data has arrived. This of course can only be done if you have code that runs when the data arrives. You might also be making mistakes when updating the DOM with the data if that is how you display it. Sometimes blank DIVs only appear after a while.
I think the title of the question is wrong and should be more along the lines of effectively repeatedly updating the DOM with data without breaking the page.

Can I load a javascript file with a partialView in asp.net-mvc?

I have an asp.net-mvc website where there is a top section with a bunch of filter information and the middle section is a reports. I now have a few different report formats and I want to toggle between a few reports. I have it working by making them all partial views and loading them via ajax (to avoid loading the common info over and over again) but one issue i realized is that some of the different reports have different javascript that goes along with them. For now, I am loading up all of the javascript files in the main parent page but I realized that I am wasting a lot of resources by download and wiring up all of the jquery events even if i never actually view a report
Is there anyway I can pass some javascript along with downloading a partial view in asp.net-mvc so I only load this and wire up the events "on demand" as required (instead of always)
Of course you can. Just be aware that the effects of the code will stick around even if you later remove the code itself: any functions you defined will remain defined, any listeners you attached will remain attached (as long as their target elements persist)... so it would be a good idea to make a setup() and teardown() methods for the loading code, that you'd invoke from your controlling code, rather than just drop a bunch of code to execute as it loads.
However, I would say it would need to be a rather unique set of circumstances for me to employ this method; for most part, it would be much easier and efficient to just load all the code you need at once, to benefit from client caching if nothing else. Toggle the behaviour of your code, don't toggle the code.

Javascript run function in background regardless the page

i need to run a function periodically regardless the page where i am. This function will get some data periodically.
I dont think that this works:
function myFunc()
{
//your code
}
//set the interval
setInterval(myFunc,2000) //this will run the function for every 2 sec.
Because it works only for the page where I am right now, so if i go to another page, function is not executed anymore.
I would like to write a function that start running when user is at index page and then is called periodically until user close the page.
Any idea? Thanks in advance!
That's not possible with javascript in the browser. When you navigate away from the page, the script will stop. You have to include a script on every page that initializes this periodical update. Or you could rewrite your application to a "single page application", which seems to be popular nowadays.
You'll need a backend application or cron-job to do that.
Another way do that would be to make an Ajax-only single page application. I guess twitter uses that model.
Depending on what your doing in the function you may be best to use a JS Worker which will run as a new thread and allow you to continue processing as much as you want in the background without having to worry about JS timeouts.
The main point here is what your asking for is near enough impossible within JS unless you use something similar to jQUery and dynamically load your pages in to a div? This would mean you still have the effect (visually) that you changing page but the browser only loads the data in.
Its very easy to in fact to load content in to a DIV using jQuery its:
$('#elementoloadid").load("/path/to/load");
You could achieve this without using jQuery but will take you longer.

Ajax: Simultaneous loading of multiple images

I have a grid of pictures (3x3, side by side, laid out in a ). I need to update this grid every so often. Since every picture independent from the rest (they get grabbed from different locations), I elected to load every picture by its own ajax callback, like so:
for (var i=0; i < numPictures; i++) {
Dajaxice.loadPicture(callback_loadPicture, {'picture_id':i})
}
The function callback_loadPicture() puts the picture into its proper place in the .
The problem is: Often, even though some picture will finish loading sooner than others, the browser will not display anything until the last ajax call is finished. Since some calls can time out, this means that I don't see anything until that single picture times out.
This behaves slightly differently in every browser: sometimes the picture will show as the callbacks finish (but usually not), sometimes the browser will show some images, but postpone showing all until the last one is finished loading.
I am using:
django 1.3 (python 2.7)
windows x64 as (test) server
dajaxice for ajax implementation
I am open to changing the structure of my code.
Any comments or suggestions will be appreciated.
Since the ajax calls are blocking as said by chrisdpratt, if you really need to display the images at the same time I would advise some kind of preloading of the 3x3 grid of images and when required by the code you can display them.
With this in mind you can run the code you already have on $(document).ready() but make the images hidden (ie display:none). When later required you would just change the display attribute on the images you need to display.
If the issue you were seeing was indeed caused by the single-threaded implementation of the Django development server, you might try django-devserver (https://github.com/dcramer/django-devserver). Amongst other improvements, it boasts:
"An improved runserver allowing you to process requests simultaneously."
The other improvements make it worth it, too!

How much content being replaced with an AJAX call is too much?

I run into a common problem when trying to do AJAX development. Where possible, I like to try and just update data in an existing layout, and not the layout itself. For example, take the div below:
<div id="content-5">Here is some content</div>
I would get the updated value for content-5 from the server and just replace the contents of content-5 with the value. This makes a lot of sense for simple data replacements where the value is always going to be displayed in its pure form.
Sometimes the content is more complicated, and I have to actually get more than just raw data... maybe there is some logic to determine how a value is displayed and perhaps the style needs to be different depending on the data inside. In that case, I generally produce the HTML on the server side and inject the HTML into the element instead of just raw data.
Example: A status field from the controller comes back as "complete", but from the design doc, "complete" is supposed to show the user the text "Available" and it needs to be styled in a way different from other statuses.
Doing this in Javascript would require some in-depth view knowledge that the template layer probably already handles. The end result would be the same (code snippet below), but the difference is that there could possibly be some code duplication and a far more complicated Javascript layer.
<div id="content-5"><span class="success">Available</span></div>
Without fail, the requirement comes up that the system will need to handle "new" contents as well. The easiest solution to implement is to just get all of the content's at the same time so that I do not need to handle the extra complexity of injecting a new element instead of just replacing existing content.
So, I create a new template, wrap the contents in another element with an ID, and bulk replace all of the content divs at the same time any time there is a change.
<div id="allContent">
<div id="content-1">Some content A</div>
<div id="content-2">Some content B</div>
<div id="content-3">Some content C</div>
<div id="content-4">Some content D</div>
<div id="content-5">Some content E</div>
</div>
At some point, I have to wonder: Where is the line? At some point it feels like I'll eventually just be replacing the whole page with an AJAX request. Would this really be a problem?
I realize this may be pretty subjective, but what are some good strategies for determining to which level you should be replacing content with AJAX? Replacing just the data seems to be my preferred method when possible as it makes the AJAX controllers very simple. Replacing larger chunks of HTML from a template seems to be the easiest for handling more complicating layout and design issues and also feels like it could be more easily maintained. Are there other options I have not considered?
I expect there will be some discussion about manipulating the DOM programatically, but I personally really dislike this. The code ends up looking pretty horrible and really starts to integrate too much layout and design into the JS layer for my liking. Since I generally work with template libraries of some sort (whether raw PHP, PHP templates like Smarty or JSP in Java) it seems to make more sense to leave as much visual design there as possible.
EDIT
Based on the first few answers, it seems like this is being read as trying to keep the user on the same page but navigating around around the site or otherwise changing the page in a radical way with each update. The question is more about how to determine where the layout work for AJAX calls should happen and whether or not it is an acceptable practice to change large chunks of code with an AJAX request, knowing that replacement code may look nearly identical to what had been there before.
I think the most important requirement is the refresh requirement. If after several AJAX updates I hit refresh, the page I was just looking at should be the page that arrives. If the page reverts to a previous state for any reason then the URL is wrong. If for any reason your AJAX data is going to make the URL in the browser invalid then you should not be using AJAX to fetch that data.
There are exceptions, of course for data the is even newer than the last AJAX request. But that's obviously not what I'm talking about. A live chat screen could receive an update between the last AJAX request and the refresh. No big deal. I'm talking about the logical content and the URL describing it should always be in sync.
Complete personal opinion ex nihil, my rule of thumb is to change no more than 1 "panel" unit or 33% of the page whichever is less.
The basis for this is that the user should be able to clearly recognise the previous page state is related to the new state - how would you feel if you were suddenly teleported into the building to your right? Be gentle with your poor user.
There are also serious technical questions about the benefits of moving and inserting basically a page worth of data, which I think is a bit of an AJAX anti-pattern. What benefit does AJAX provide if you're going to do that?
Your specific question seems dependant on the supposition that the response coming back from your AJAX request isn't "just" data. This feels wrong to me from a separation of concerns point of view: I would expect a page to have all the layout information it requires already, the AJAX response itself to provide nothing more than dumb data/markup, and the JS event handler which created the request to sew the two together, MVC style. In that respect I think, yes, you're doing too much.
(by panel, I mean one logical design element - a menu, a ribbon, an item metadata panel, etc..)
edit: now that I think about it, I think SO's user profile page breaks my rule of thumb with those tab clicks
Depending on whether you want people to be able to to link to / bookmark etc the current page, you might want to navigate the user's browser.
This isn't a concern for some apps like GMail etc, and they won't ever refresh the page.
For myself, I tend to think it's a good practice to navigate the browser when navigating to a logically different place. eg. a person's profile vs. a list of their messages.
Sorry if this is vague, it's rather subjective :-)
A good guideline for something like this is to ask yourself, "Is this dynamic application 'content', or is it content-content?" Your use case sounds like application content that will change with each user. This is probably the best place for Ajax, but with everything, it's always nice not to just have one hammer. You don't want to do too much on one page. For instance, if one part breaks, the entire thing might, thereby frustrating the user.
Anywhere you're looking at actual page content or anything where the information is static, I strongly suggest avoiding the use of JavaScript, as it runs the risk of being invisible to search engines. Make sure anything linking to information like this is crawlable. The first step towards this is dynamic generation on the server side rather than browser side.
If you're using Smarty templates to produce a page, just fragment a template into various meaningful sections - news.tpl, email.tpl, weather.tpl - and have a master.tpl producing the structure of the page and calling child templates.
Then, if you're for example using an AJAX call triggered by a timeout to refresh the news, you can just call the server, cram the necessary data into news.tpl, and return the results into the news div you set up with master.tpl. This way your news layout is always following the pattern of news.tpl. (If you used JavaScript to manipulate formatting bits or set up event handling on document load, you'll need to attach that post-processing to fire after the AJAX call.)
You haven't really gotten specific about the types of things you're trying to replace here, and my initial reaction is that, if a single event is triggering multiple sections of the page to update at once, that's a sign that maybe you should be coallating those sections into a single display.
How much formatting gets done on the server end versus how much gets done on the client end with JavaScript? I'd say server-side formatting if possible, that way you have code that reflects discussions you've made about display layout and logic. Client-side formatting can be used for more interface-based issues - sorting rows in a table and alternating row colors with :odd and :even selectors, showing and hiding divs to create a "tabbed display" without hitting the server since the data won't change just from selecting a new tab, that sort of thing.
Finally, AJAX is one-way. If your web page is a view on a database, this isn't as much of a problem, but using AJAX manipulation to take the place of normal navigation is a terrible idea.
If you were habitually replacing the entire contents of a page using AJAX calls, I would agree that you have a problem. However, it appears to me that you are attempting to carefully think through the implications of your design and attempting, where possible, to avoid what annakata has called this "AJAX anti-pattern."
My rule is a bit simpler: as long as a substantial amount of context (e.g. menu on the left, header, various controls, page title, etc.) remains on a page, I am Ok with replacing almost anything with an AJAX call. That being said, I've never struggled with a page that has as much AJAX-generated code as you are.
I do have one question though: isn't it possible to encode state so that you can just replace some of the Divs in your example rather than all of them? If not, have you thought about doing so?

Categories

Resources