Unresponsive javascript notification - javascript

I have a situation where I render items from server in GWT grid on FireFox 3.6+. I have approximately 200 items and I load them in loop:
users = myService.getUsers();
for(User user : users){
myPanel.addUser(user); // Pseudocode. Actually i add some labels and text fields...
}
It tooks a long time to change DOM in this loop, so I got "Unresponsive script" notification. But I can not refactor code or make pagination, I need all 200 items on 1 page loaded at once.
Are there any ways to suppress this notification? To notify browser that my script is not hang, but doing something useful?
UPD Ok, here is my code closer. It is a code from big project, and we have many custom components, so, I think, it has no real value.
myService.getUsersDetails(searchCriteria, new MyCallback<List<User>>)
{
#Override
protected void response(List<User> result)
{
gridExpanderPresenter.clear();
int i = 0;
for (User user: result)
{
UserDetailsView detailsView = detailsViewProvider.get();
gridExpanderPresenter.setPresenter(UsersPresenter.this);
gridExpanderPresenter.add(detailsView.asWidget()); //Here is DOM manipulation i mentioned
if (i++ % 2 == 1)
{
detailsView.setOdd(); //Setting style here
}
detailsView.setData(user);
}
}
});
And I think this can help me...

You should add Users before attaching myPanel to the DOM, or if it's already attached and needs to be updated, remove myPanel from the DOM, add all users and reattach myPanel.
What happens when you add 200 users while myPanel is attached is that your browser has to update DOM 200 times which is quite costly (recalculating and repainting the screen).

Several options:
batch your updates using Scheduler.scheduleIncremental; rendering only 10 users or so at a time (don't worry, the Scheduler will run your code as many times as possible in a row before yielding, so it might actually render 50, 100 or 150 users at a time, and then continue 10ms (yes, milliseconds) after)
switch to CellTable; this is a major refactoring, but it'll give you much better performance than anything else you could do based on widgets (Label, TextBox, etc.)

Related

Test a self deleting/dynamic Webelement in Selenium

What I'm doing
I've been experimenting with Selenium and making a simple program to make my Selenium testing life easier. Part of this is testing webelements and figuring out what methods (clicking submitting ect) make them reload the page, remain static, or become stale without reloading the page. In this question I'm particularly interested in the third case as the first two are already implemented by me.
The problem I'm having
The problem I have is finding a Webelement that goes stale and doesn't cause a page reload. I can't think of a good way to search for one, I don't have the HTML and javascript skills to make one (yet anyways) and I can't verify my code works unless I actually test it.
What I've done/tried
The first thing I thought to look for was a popup but those aren't actually part of the webpage and they're also quite unreliable. I want something thats going to behave consistently because otherwise the test won't work. I think dynamic Webelements, those that change their locators when acted upon will suit my needs but I have no good way of finding them. Any google results for "Self deleting webelement exmaple" or "Webelement goes stale doesn't cause page reload example" or similar, will only give me questions on stackoverflow like this one rather than what I want - concrete examples. The code I'm running simply waits for a staleReferenceException and for an onload event in javascript. If the staleReferenceException occurs but the onload event does not, then I know I've found a self-deleting / dynamic webelement (at least thats what I think is the proper way to detect this). Here is the code I'm running:
try {
//wait until the element goes stale
wait.until(ExpectedConditions.stalenessOf(webElement));
//init the async javascript callback script
String script = "var callback = arguments[arguments.length - 1];" +
"var classToCall = 'SeleniumTest.isPageReloaded';" +
"window.addEventListener('onload'," + "callback(classToCall));";
//execute the script and wait till it returns (unless timeout exceeded)
JavascriptExecutor js = (JavascriptExecutor) driver;
//execute the script and return the java classname to call
//if/when the callback function returns normally
String classToCall = (String) js.executeAsyncScript(script);
clazz = Class.forName(classToCall);
callbackMethod = clazz.getMethod("JavascriptWorking");
callbackMethod.invoke(null,null);
//page reloaded
threadcase = 1;
}
//waiting until webElement becomes stale exceeded timeoutSeconds
catch (TimeoutException e) {
//page was static
threadcase = 2;
}
//waiting until webElement Reloaded the page exceeded timeoutSeconds
catch (ScriptTimeoutException e) {
//the webElement became stale BUT didn't cause a page reload.
threadcase = 3;
As you can notice above there is an int variable named threadcase in this code. The three 'cases' starting from 1 (0 was the starting value which represented a program flow error) represent the three (non-error) possible results of this test:
the page reloads
the page remains static, webelement doesn't change
the page remains static, webelement changes
And I need a good example with which to test the third case.
Solutions I've considered
I've done some basic research into removing webelements in javascript but I A: don't even know if I can act on the page in Selenium like that and B: I'd rather get a test case that just uses the Webpage as is since introducing my edits makes the validity of my testcase reliant on more of my code (which is bad!). So what I need is a good way of finding a webelement that matches my criteria without having to scour the internet with the f12 window open hoping to find that one button that does what I need.
Edit 1
I just tried doing this test more manually, it was suggested in an answer that I manually delete a webelement at the right time and then test my program that way. What I tested was the Google homepage. I tried using the google apps button because when clicked it doesn't cause the whole page to reload. So my thinking was, I'll click it, halt program execution, manually delete it, run the rest of my code, and since no onload events will occur, my program will pass the test. To my suprise thats not what happened.
The exact code I ran is the below. I had my debug stop on the first line:
1 Method callbackMethod = null;
2 try {
3 //wait until the element goes stale
4 wait.until(ExpectedConditions.stalenessOf(webElement));
5 //init the async javascript callback script
6 String script = "var callback = arguments[arguments.length - 1];" +
7 "var classToCall = 'SeleniumTest.isPageReloaded';" +
8 "window.addEventListener('onload', callback(classToCall));";
9 //execute the script and wait till it returns (unless timeout
10 //exceeded)
11 JavascriptExecutor js = (JavascriptExecutor) driver;
12 //execute the script and return the java classname to call if/when
13 //the callback function returns normally
14 String classToCall = (String) js.executeAsyncScript(script);
15 clazz = Class.forName(classToCall);
16 callbackMethod = clazz.getMethod("JavascriptWorking");
17 callbackMethod.invoke(null,null);
18 //page reloaded
19 threadcase = 1;
20 }
21 //waiting until webElement becomes stale exceeded timeoutSeconds
22 catch (TimeoutException e) {
23 //page was static
24 threadcase = 2;
25 }
26 //waiting until webElement Reloaded the page exceeded
27 //timeoutSeconds
28 catch (ScriptTimeoutException e) {
29 //the webElement became stale BUT didn't cause a page reload.
30 threadcase = 3;
31 //trying to get the class from javascript callback failed.
32 }
whats supposed to happen is that a Stale webelement causes the program to stop waiting on line 4, the program progresses, initializes the Javascript callback in lines 6-11 and then on line 14 the call to executeAsyncScript is SUPPOSED to wait untill an 'onload' event which should only occur if the page reloads. Right now its not doing that or I'm blind. I must be confusing the program flow because I'm 99% certain that there are no page reloads happening when I manipulate the DOM to delete the webelement I'm clicking on.
This is the URL I'm trying:
https://www.google.com/webhp?gws_rd=ssl
Simple google homepage, the button I'm deleting is the google apps button (the black 9-grid in the top right)
some info on that element:
class="gb_8 gb_9c gb_R gb_g"
id="gbwa"
Its the general container element for the button itself and the dropdown it creates. I'm deleting this when my program hits the STOP on line 1. Then I go through my program in the debugger. Note (you may have to click inspect element on the button more than once to focus in on it). I'm going to try deleting lower level elements rather than the whole container and see if that changes anything but still this behavior baffles me. The goal here is to get the program flow to threadcase 3 because thats the one we are testing for. There should be no page reloads BUT the webelement should become stale after I manually delete it. I don't have any clue why the javascript callback is running when I can't see a page reload. Let me know if you need more info on what exactly I'm deleting on the google homepage and I'll try sending a picture (with optional freehand circles of course).
I would think that you could debug through a test, place a breakpoint at a suitable point, then use the browsers dev tools to manually update the HTML.
Obviously, if you want this to be a repeatable process it is not an option, but if you are just investigating, then a manual intervention could be suitable

Preload multiple (798) audio files in Chrome

I making a game and I want to load 798 sound files, but there is a problem only in Chrome, Firefox fine. Sample code: https://jsfiddle.net/76zb42ag/, see the console (press F12).
Sometimes script loads only 100, 500, 700 files, sometimes is fine. If i reduce the number of files to ex. 300 is ok (always). How can I solve this problem? I need a callback or any ideas? The game will be offline (node webkit).
Javascript code :
var total = 0;
// sample file to download: http://www.sample-videos.com/audio/mp3/crowd-cheering.mp3
// sounds.length = 798 files
var sounds = [
(...limit character, see https://jsfiddle.net/76zb42ag/...)
];
for (var i in sounds) {
load(sounds[i]);
}
function load(file) {
var snd = new Audio();
snd.addEventListener('canplaythrough', loadedAudio, false);
snd.src = file;
}
function loadedAudio() {
total++;
console.log(total);
if (total == sounds.length){
console.log("COMPLETE");
}
}
This isn't really a code problem. It's a general architecture problem.
Depending not only on the number, but also the size of the samples, it's going to be unlikely you can get them all loaded at once. Even if you can, it'll run very poorly because of the high memory use and likely crash the tab after a certain amount of time.
Since it's offline, I would say you could even get away with not pre-loading them at all, since the read speed is going to be nearly instantaneous.
If you find that isn't suitable, or you may need like 5 at once and it might be too slow, I'd say you'll need to architect your game in a way that you can determine which sounds you'll need for a certain game state, and just load those (and remove references to ones you don't need so they can be garbage collected).
This is exactly what all games do when they show you a loading screen, and for the same reasons.
If you want to avoid "loading screens", you can get clever by working out a way to know what is coming up and load it just ahead of time.

Tab-to-tab communication using BreezeJS and localStorage

I'm using BreezeJS and storing/restoring data in local storage. That's working great. The problem occurs when the user opens multiple tabs. Changes in each tab clobber each other. Changes should be synchronised between tabs.
NB: BreezeJS will take care of merging changes, I just need to deal with race conditions between tabs.
var stashName = 'stash_everything';
window.setInterval(function () {
var exportData = manager.exportEntities();
window.localStorage.setItem(stashName, exportData);
}, 5000);
addEvent(window, 'storage', function (event) {
if (event.key == stashName) {
var importData = window.localStorage.getItem(stashName);
manager.importEntities(importData);
}
});
I've tried listening to the 'storage' event, but I haven't been able to get it working successfully. I either still clobber changes, or get into an infinite loop.
The crux of the issue is that I'm just saving on a timer; if I only saved after user interaction, then I'd avoid (most) race conditions. There's no 'has the user changed anything since last time I asked you' call in breeze, though, as far as I can tell.
Does anyone have advice on how to approach this?
Hmm this doesn't seem like it is impervious to having problems for many reasons but the main one would be that you still won't prevent concurrent saves from each tab with different data sets. That being said, if you are comfortable with the fact the two caches could be out of sync just use some unique identifier -
Somewhere in your app on load -
var stashName = 'stash-everything-' + new Date().getTime();
window.setInterval(function () {
var exportData = manager.exportEntities();
window.localStorage.setItem(stashName, exportData);
}, 5000);
Now each tab would have a unique set of data to work with.

multiple Javascript run in parallel

I have a quite complex .Net page with an intensive usage of a third party libraries (DevExpress).
My page is composed of several parts:
A "Result Browser" to let user select the content of two widgets:
A Table widget
A Graphic widget
A timer (AspxTimer) to refresh the "Result browser" contents
A time widget which gives time every second
I make an intensive use of CallBacks (AspxCallBack) to minimize the volume of data to transfer from/to the server for the refresh of the browser/table and graphic.
During tests, each element separately is working well but one of the feature of the table is to re-calculate sub totals of the table when user click on a specific button. I have marked the correct subTotal cells (containing the span) during table construction with appropriate properties so I can find them on client side with javascript (<span ... SubTotal='true'>0.0</span>) and have a vector of class (code, number) to store actual numbers do recalculate subTotal from.
. Here is my code:
function recalcSubTotal() {
$('span[SubTotal="true"]').each(function() {
var subSpan = $(this);
var sTrends = subSpan.attr('trendsTotal');
var Trends = sTrends.split('|');
var subTotal = 0.0;
for (var i = 0; i < Trends.length - 1; i++) {
subTotal += Decision[Trends[i]];
}
subSpan.html(subTotal.toFixed(1));
});
}
This works pretty well in an isolated page but when mixing all this stuff in a single page I randomely have NaN (Not a numer) codes returned by this func or wrong totals, click again the action button and it can work correctly. Nothing else but the relative complexity and parallel usage of javascript+callbacks can really explain this behavior. I managed to avoid any parallel Callback (chaining them) but can't do that with client side events or date/time timer. I wonder If there is a general clean way of dealing with client side parallel run (timer+callbacks+user actions).
Thanks for any clue on this topic.
Try to call your function recalcSubTotal() with the methode setTimeout(), like this :
setTimeout(function(){
recalcSubTotal();
}, 0);

LightSwitch HTML Client to automatically run queries without refreshing entire page

In Lightswitch HTML client we have created a screen to display the work in progress for a particular business processes.
This is to be displayed on a big screen, much like when you go to Argos to collect your order. Here's a screenshot...
We are using some java script to refresh the page every 30 seconds.
setTimeout(function () {
window.location.reload(1);
}, 30000);
However, there are two issues with this.
The 'maximum number of results' text input by the user is lost on refresh.
It doesnt look nice to refresh the whole page.
Is it therefore possible to just trigger each query to reload instead of the entire page?
(The data is provided to LightSwitch by a WCF RIA Service)
In the JavaScript, use screen.MyList.load(). It will reload the list asynchronously.
Note that IntelliSense does not always suggest list names on the screen object but will recognize them if you type the name.
Combined with the setTimeout() method and the created screen event, it should work.
I had the same issue and finally found the solution. I added this in my created event:
myapp.BrowseMembers.created = function (screen) {
setInterval(function () {screen.Members.load(true);}, 1000);
};
Ii works, just the screen get flickering when reloading the data.
setTimeout will only trigger once but setInterval will trigger every 1 second.
I had the same problem with LightSwitch VS2012 Update 3,
for my case just invalidation is enough, so i can always work with a fresh entity.
This code runs once on entry screen and invalidates loaded entities every 30 seconds, and forces a refetch just when needed.
myapp.aaHome.created = function (screen) {
setInterval(function () {
screen.details.dataWorkspace.ApplicationData.Currencies._loadedEntities = {};
}, 30000);
};

Categories

Resources