Chrome slow to load resources `(from disk cache)` - performance

My site http://www.front-end.io configures the HTTP requests to load resources from cache with first priority. So my header will be like:
cache-control:max-age=315360000
ETag:W/"11913b-ks0rwRQM+ijHcl1HDuse3g"
Chrome indeed does not initiate any request (even 304) to the server, it loads from the cache directly:
It takes my Windows10 Chrome >400ms to load the js file from local disk.
My Ubuntu Chromium also takes >100ms.
But FireFox takes around 10ms only!
I found this question as well, Google Chrome load image from cache slower than download, but there are not explanations.
Could anybody help? Thanks.

Probably that is wrong timing information.
In order to Chrome Dev Tools such as Timeline display correct information you must disable extensions to exclude noise that they produce. Relevant excerpt from How to Use the Timeline Tool article by Kayce Basques:
Disable extensions. Chrome extensions can add unrelated noise to
Timeline recordings of your application. Open a Chrome window in
incognito mode, or create a new Chrome user profile to ensure that
your environment has no extensions.
Although some extensions can intercept resource requests in blocking fashion Grammarly is not one of those extensions. It doesn't have required webRequestBlocking permission specified in manifest file. Check chrome.webRequest page for more information.
If you measure time that took browser to get /vendor.61e0ab918e699695d3a3.js script from disk cache, compile and execute it you will see that it is pretty much constant regardless of whether Grammarly enabled or disabled. You can use code snippet below:
<script>var startTime = performance.now();</script>
<script type="text/javascript" src="/vendor.61e0ab918e699695d3a3.js"></script>
<script>
var endTime = performance.now();
console.log("Time: " + (endTime - startTime) + " [ms].")
</script>

Related

Prevent external files in src of iframe from being cached (with CloudFlare)

I am trying to make a playground like plunker. I just noticed a very odd behavior on production (with active mode in Cloudflare), whereas it works well in localhost.
By iframe, the playground previews index_internal.html which may contain links to other files (eg, .html, .js, .css). iframe is able to interpret external links such as <script src="script.js"></script>.
So each time a user modifies their file (eg, script.js) on the editor, my program saves the new file into a temporary folder on the server, then refresh the iframe by iframe.src = iframe.src, it works well on localhost.
However, I realized that, in production, the browser always keeps loading the initial script.js, even though users modify it in the editor and a new version is written in the folder in the server. For example, what I see in Dev Tools ==> Network is always the initial version of script.js, whereas I can check the new version of script.js saved in the server by less on the left hand.
Does anyone know why it is like this? And how to fix it?
Edit 1:
I tried the following, which did not work with script.js:
var iframe = document.getElementById('myiframe');
iframe.contentWindow.location.reload(true);
iframe.contentDocument.location.reload(true);
iframe.contentWindow.location.href = iframe.contentWindow.location.href
iframe.contentWindow.src = iframe.contentWindow.src
iframe.contentWindow.location.replace(iframe.contentWindow.location.href)
I tried to add a version, it worked with index_internal.html, but did not reload script.js:
var newSrc = iframe.src.split('?')[0]
iframe.src = newSrc + "?uid=" + Math.floor((Math.random() * 100000) + 1);
If I turn Cloudflare to development mode, script.js is reloaded, but I do want to keep Cloudflare in active mode.
I found it.
We can create a custom rule for caching in CloudFlare:
https://support.cloudflare.com/hc/en-us/articles/200168306-Is-there-a-tutorial-for-Page-Rules-#cache
For example, I could set Bypass as Cache Level for the folder www.mysite.com/tmp/*.

How does React deal with pre-compiled HTML from PhantomJS?

I compiled my reactjs using webpack and got a bundle file bundles.js. My bundles.js contains a component that make API calls to get the data.
I put this file in my html and pass the url to phantom.js to pre-compile static html for SEO reasons.
I am witnessing something strange here, the ajax calls for APIS are not getting fired at all.
For example, I have a component called Home which is called when I request for url /home. My Home component makes an ajax request to backend (django-rest) to get some data. Now when I call home page in phantomjs this api call is not getting fired.
Am I missing something here?
I have been using React based app rendering in Phantomjs since 2014. Make sure you use the latest Phantomjs version v2.x. The problems with Phantomjs occur because it uses older webkit engine, so if you have some CSS3 features used make sure they are prefixed correctly example flexbox layout.
From the JS side the PhantomJS does not support many newer APIs (example fetch etc.), to fix this add the polyfills and your fine. The most complicated thing is to track down errors, use the console.log and evaluate code inside the Phantomjs. There is also debugging mode which is actually quite difficult to use, but this could help you track down complex errors. I used webkit engine based browser Aurora to track down some of the issues.
For debugging the network traffic, try logging the requested and received events:
var page = require('webpage').create();
page.onResourceRequested = function(request) {
console.log('Request ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function(response) {
console.log('Receive ' + JSON.stringify(response, undefined, 4));
};

concert ways to improve loading time in Android WebView

I am trying all means to improve the loading time of an link in android webview in vain.I am using a link which has images and text fetched from external server by using some js functions and those images and text may change on any moment.In this scenario the code I used is as below.I am not interested in HTML 5 caching or server caching techniques,as the same link loads faster on browser fails to do the same in android webview.There is not much js script i can load from resource to improve performance hence most of the script just pulls data from external server and images from on amazon server.
WebSettings settings = getSettings();
settings.setJavaScriptEnabled(true);
settings.setPluginState(PluginState.ON);
settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
settings.setDomStorageEnabled(false);
settings.setLoadsImagesAutomatically(true);
settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
settings.setJavaScriptEnabled(true);
settings.setAppCacheEnabled(false);
settings.setGeolocationEnabled(false);
1 .I guess turning on DomStaorage and AppCache to true have impact on loading time so i have turned it off. -> Is this true
2.In OnDestroy i call clearcache on webview to clear application cache - I am doing this hence i am afraid that my app size may grow as webview db grows if i fail to clear.-> is this must,or android handles this gracefully.
3.Few suggestion i hear is to set setCacheMode to LOAD_NO_CACHE and comment clearing webview cache in onDestroy. --> Does calling webview.clearcache() have any impact hence I have already set not to load from cache.
4.The link does not provide me information of previously refreshed time,in that case what cache mode could any one recommend.
5.Is there is any concert testing method to find out loading time on devices that takes network connection and server lags into account.hence the same page once it loads fast may load slow in some other time.
Give a try with "fast click".
mobile browsers will wait approximately 300ms from the time that you tap the button to fire the click event. The reason for this is that the browser is waiting to see if you are actually performing a double tap.
Download the script, add
<script type='application/javascript' src='fastclick.js'></script>
in your header and this code in your script.
window.addEventListener('load', function() {
FastClick.attach(document.body);
}, false);
More informations: https://developers.google.com/mobile/articles/fast_buttons

Flash + fancy uploader.. have to click twice on firefox

http://digitarald.de/project/fancyupload/3-0/showcase/attach-a-file/
That's the uploader plugin I'm using.
If you go there in firefox, you'll notice you have to click "attach a file" twice before it works. It seems to work fine in every other browser (that I've tested).
it's creating a flash object, and I'm not sure how to go about making it so you only click once in FF.
I'm not familiar with mooTools, but have you tried something like this? (attempted to write it in mooTools, but have no idea what I'm doing).
$('uploadLink').addEvent('click', function(){
if(Browser.firefox) $('uploadLink').fireEvent('click');
});
or I suppose if it has to wait for the flash to be created, something like this:
$('uploadLink').addEvent('click', function(){
if(Browser.firefox){
var flashTimer = setTimeout(function(){
clearTimeout(flashTimer);
/// or however you make sure the flash has successfully been added to the page
if($('flashContainer').getElements().length) $('uploadLink').fireEvent('click');
},100);
}
});
There's always the possibility that FF's security measures won't let you do something like this (mouse interactions with flash can be potentially harmful, as flash has FS access and stuff).
Depending on what your backend is, I'm highly in favor of skipping flash for file uploads when possible. One very well written plugin for such a task is available here:
http://valums.com/ajax-upload/
Good luck!

How to Stop the page loading in firefox programmatically?

I am running several tests with WebDriver and Firefox.
I'm running into a problem with the following command:
WebDriver.get(www.google.com);
With this command, WebDriver blocks till the onload event is fired. While this can normally takes seconds, it can take hours on websites which never finish loading.
What I'd like to do is stop loading the page after a certain timeout, somehow simulating Firefox's stop button.
I first tried execute the following JS code every time that I tried loading a page:
var loadTimeout=setTimeout(\"window.stop();\", 10000);
Unfortunately this doesn't work, probably because :
Because of the order in which scripts are loaded, the stop() method cannot stop the document in which it is contained from loading 1
UPDATE 1: I tried to use SquidProxy in order to add connect and request timeouts, but the problem persisted.
One weird thing that I found today is that one web site that never stopped loading on my machine (FF3.6 - 4.0 and Mac Os 10.6.7) loaded normally on other browsers and/or computers.
UPDATE 2: The problem apparently can be solved by telling Firefox not to load images. hopefully, everything will work after that...
I wish WebDriver had a better Chrome driver in order to use it. Firefox is disappointing me every day!
UPDATE 3: Selenium 2.9 added a new feature to handle cases where the driver appears to hang. This can be used with FirefoxProfile as follows:
FirefoxProfile firefoxProfile = new ProfilesIni().getProfile("web");
firefoxProfile.setPreference("webdriver.load.strategy", "fast");
I'll post whether this works after I try it.
UPDATE 4: at the end none of the above methods worked. I end up "killing" the threads that are taking to long to finish. I am planing to try Ghostdriver which is a Remote WebDriver that uses PhantomJS as back-end. PhantomJS is a headless WebKit scriptable, so i expect not to have the problems of a real browser such as firefox. For people that are not obligate to use firefox(crawling purposes) i will update with the results
UPDATE 5: Time for an update. Using for 5 months the ghostdriver 1.1 instead FirefoxDriver i can say that i am really happy with his performance and stability. I got some cases where we have not the appropriate behaviour but looks like in general ghostdriver is stable enough. So if you need, like me, a browser for crawling/web scraping purposes i recomend you use ghostdriver instead firefox and xvfb which will give you several headaches...
I was able to get around this doing a few things.
First, set a timeout for the webdriver. E.g.,
WebDriver wd;
... initialize wd ...
wd.manage().timeouts().pageLoadTimeout(5000, TimeUnit.MILLISECONDS);
Second, when doing your get, wrap it around a TimeoutException. (I added a UnhandledAlertException catch there just for good measure.) E.g.,
for (int i = 0; i < 10; i++) {
try {
wd.get(url);
break;
} catch (org.openqa.selenium.TimeoutException te) {
((JavascriptExecutor)wd).executeScript("window.stop();");
} catch (UnhandledAlertException uae) {
Alert alert = wd.switchTo().alert();
alert.accept();
}
}
This basically tries to load the page, but if it times out, it forces the page to stop loading via javascript, then tries to get the page again. It might not help in your case, but it definitely helped in mine, particularly when doing a webdriver's getCurrentUrl() command, which can also take too long, have an alert, and require the page to stop loading before you get the url.
I've run into the same problem, and there's no general solution it seems. There is, however, a bug about it in their bug tracking system which you could 'star' to vote for it.
http://code.google.com/p/selenium/issues/detail?id=687
One of the comments on that bug has a workaround which may work for you - Basically, it creates a separate thread which waits for the required time, and then tries to simulate pressing escape in the browser, but that requires the browser window to be frontmost, which may be a problem.
http://code.google.com/p/selenium/issues/detail?id=687#c4
My solution is to use this class:
WebDriverBackedSelenium;
//When creating a new browser:
WebDriver driver = _initBrowser(); //Just returns firefox WebDriver
WebDriverBackedSelenium backedSelenuium =
new WebDriverBackedSelenium(driver,"about:blank");
//This code has to be put where a TimeOut is detected
//I use ExecutorService and Future<?> Object
void onTimeOut()
{
backedSelenuium.runScript("window.stop();");
}
It was a really tedious issue to solve. However, I am wondering why people are complicating it. I just did the following and the problem got resolved (perhaps got supported recently):
driver= webdriver.Firefox()
driver.set_page_load_timeout(5)
driver.get('somewebpage')
It worked for me using Firefox driver (and Chrome driver as well).
One weird thing that i found today is that one web site that never stop loading on my machine (FF3.6 - 4.0 and Mac Os 10.6.7), is stop loading NORMALy in Chrome in my machine and also in another Mac Os and Windows machines of some colleague of mine!
I think the problem is closely related to Firefox bugs. See this blog post for details. Maybe upgrade of FireFox to the latest version will solve your problem. Anyway I wish to see Selenium update that simulates the "stop" button...
Basically I set the browser timeout lower than my selenium hub, and then catch the error. And then stop the browser from loading, then continue the test.
webdriver.manage().timeouts().pageLoadTimeout(55000);
function handleError(err){
console.log(err.stack);
};
return webdriver.get(url).then(null,handleError).then(function () {
return webdriver.executeScript("return window.stop()");
});
Well , the following concept worked with me on Chrome , try the same:
1) Navigate to "about:blank"
2) get element "body"
3) on the elemënt , just Send Keys Ësc
Just in case someone else might be stuck with the same forever loading annoyance, you can use simple add-ons such as Killspinners for Firefox to do the job effortlessly.
Edit : This solution doesn't work if javascript is the problem. Then you could go for a Greasemonkey script such as :
// ==UserScript==
// #name auto kill
// #namespace default
// #description auto kill
// #include *
// #version 1
// #grant none
// ==/UserScript==
function sleep1() {
window.stop();
setTimeout(sleep1, 1500);
}
setTimeout(sleep1, 5000);

Resources