I'm trying to speed up response times in my ajax web application by doing the following:
Say the user requests a page whose contents don't change (e.g a web form). When the user makes a different request, I 'cache' the form by putting it in a hidden div. Before displaying the new information. So the form is basically still loaded in the browser but not visible to the user. If the user requests the same form again, it gets loaded from the hidden div. That's notably faster than doing a round-trip to the server for the form.
I do realise doing so with lots of data will probably degrade performance as the browser gets to keep a lot in memory. But I will place a limit on how much gets "cached" this way.
Now, I came up with this on my own which is why I'd like to know if there is a better/established way of doing this. It works as expected but I don't know what the possible drawbacks are (security-related perhaps?).
I would appreciate any suggestions.
Many thanks.
I've done this before. It can be a useful technique. Just make sure the data is accurate and that you support JS disabled user agents.
EDIT: And that there is no better solution.
Storing the HTML code for your form in a JS variable is probably more efficient than having a hidden div with the interpretation of this HTML code (form + form fields + various markup).
If your form code is generated at the same time as the page, simply print it in a JS variable :
<script language="javascript">
var myFormCode = '<? echo $myFormCode; ?>';
</script>
(That's if you use PHP...other languages shouldn't be far from that)
If your form code is generated later, you can send it as text via JSON :
<?php
echo json_encode($myFormCode);
?>
...and then build your form when needed, with something like that on the client side :
<script language="javascript">
myRealFormDiv.innerHTML = eval(myJSONEncodedTextIGotViaAJAX);
</script>
JS code is obviously not exactly what you need to type in, but you probably see my point.
This should work and is the best solution I can think of. Whether there are any security implications really depends on your forms and how they work - nobody will be able to diagnose this without actual code.
What about use APC or Memcached ?
They'll allow you to keep the html markup clean, with not 'hidden tricks' that could potentially create problems (user dont have css enabled? use IE6? what about accessibility?)
Depends on your needs, but in general way the page must contain just what it must containt, nothing else.
Another way of doing this is to set the "Expires" or "Cache-Control" HTTP headers for the form.
If you set an "Expires" header 1 hour in the future for url http://example.com/form.html, then the next time within an hour that the user navigates to that form the HTML will be loaded without touching the server.
If you properly version your images/CSS/JS and give them far-future "Expires" headers as well, then there will be no server roundtrip, plus you'll help the performance the rest of your pages.
Related
I assume the answer is: "it is not possible because php is server language not client language", but I would like someone more expert than me to state this and eventually list all possible workarounds...
Question: is it (at all) possible to have a php function executed (only) when the user "clicks" or performs some other kind of action (e.g. mouse-over) in an html page without using any javascript?
(P.S. As a workaround I considered to access an intermediate page containing the php code to be executed when the client action occurs and then redirect as needed but this is not straightforward as far as passing the results of the php code goes.)
In general no. The only workaround regarding mouse-overs I can possibly think of would be a small 1x1 transparent background image that is generated by a PHP script and that is only shown if a user hovers over a certain element.
html:
<div id="mouseover_php">execute php</div>
css:
#mouseover_php:hover {
background-image:url(/path/to/php-script)
}
php:
<?php
// your code
// set http headers to correct content type and to disable caching
// output 1x1 pixel transparent image
But as all modern browsers use pre-fetching and caching (although this can be influenced by setting the Cache Control header) I certainly would not rely on this as an unquestionable indicator for a mouse-over event. So this would be, if anything, a very unclean hack.
Regarding clicks: Here the only possible way is to load an intermediate page, just as you proposed it. As far as I am concerned there is no way to achieve this without AJAX.
This is not possible without making a new request.
You must use a link to send the user to a new page (or the same page -- anything as long as a new request is made), or you must use something like AJAX.
There is actually one very hack-ish way I can think of. It's not exactly pretty, but it should work.
You could use an iframe as the target for a link. Basically instead of a link opening in the same or a new window, it would open in a hidden iframe.
Untested, but in theory:
<iframe name="testframe" id="testframe"></iframe>
Test
Edit: After some rough testing, it looks like chrome will not obey this. IE9 will to some extent though, it seems.
I have recently been debating whether or not to use AJAX for my site navigation to only transfer over only needed updated HTML elements, or if there was not a significant difference between new elements and current elements to just load the page in its entirety (php generated or static html)
However, I thought how that if the new content was not large in size relative the current page...that perhaps I should send it has a hidden div (via CSS) along with the current page.
This 3rd way seems like a simple solution. For example just send the entire current page + any additional content that might be requested by the user as hidden divs.
When the user selects the content just hide the current content, and display the hidden content...
All in all, each way (normal, Ajax, CSS) would look the same to the user but a CSS / Javascript solution would be provide the quickest interface and be the simplest. Ajax might cut down on download for example if the content is never used.
This is a validation question. Is this a valid way to navigate a web application? By hiding/displaying divs using the display property or opacity property to flip through content?
Notes (response to answers)
The Hidden divs would be static data that is not changed by the user. I thought this would be obvious but now I've made it explicit.
Thanks!
You need to think about it this way.
If the hidden content is dynamic (changing) there is a need for AJAX because AJAX would usually be used to fetch updated content from the DB.
If your content is static (not changing) then how much new content are we talking? Does the size of the new content have a significant impact on render time if it was in a hidden DIV? If its very little, then I would say use a hidden DIV. If its alot, then mabye it's time to consider AJAX to load it in from an external page.
Here is a simple solution to get you started using a hidden DIV:
<script>
function setVisibility(id, visibility){
document.getElementById(id).style.display=visibility;}
</script>
<div id="message1" onclick="setVisibility('message1', 'none');setVisibility('message2', 'inline');"> >Hey What's Up?</div>
<div style="display:none;" id="message2">Not Much You?</div>
It does depend on the data being shown. Facebook could not do this because the data is updated often, there would be out of sync problems.
Since i do most of the development by myself, having a full ajaxy site seems like a large task for me, so i usually keep page flips, but some of the content on the inside i have it as ajax generated.
Like say there is a form to create something, i have that form submit in the background (excellent jquery plugin for that) then i have the new data be displayed at the top of the list ($.prepend). This way, things are still ajaxed, but not to a level of which is hard to manage for a single programmer.
One thing you need to keep in mind is to keep your site as non-breakable and accessible as possible. Because Ajax content isn't on the page, it can't be indexed by spiders, etc. Ajax requires more error testing/catching, etc than "standard" CSS alteration, so make sure you're going to make it work in ALL browsers. There's no excuse for bad or broken navigation.
Your idea is definitely a valid approach. You're basically looking for a trade-off between an initial, longer request, and many shorter ones down the line. As long as the amount of initially hidden content is not gratuitous, the user experience will likely benefit by getting all of the markup first, and hiding/showing it with JavaScript + CSS as needed.
Suggested Approach: Consider using jQuery's
hide()
show()
or toggle()
methods, and combining with a history manager to emulate real browser history changes as the user navigate's page states. This is the approach I use on my website: paislee.net. IMO its clean and lightning fast because there are no new HTTP requests.
Hey guys quick question, I am currently echoing a lot of javascript that is based conditionally on login status and other variables. I was wondering if it would be better to simply echo the script include like <script type="text/javascript" src="javascript/openlogin.js"></script> that has been run through a minifying program and been gzipped or to echo the full script in raw format. The latter suggestion is messier to me but it reduces http requests while the latter would probably be smaller but take more cpu? Just wondering what some other people think. Thanks in advance for any advice.
I would go the first option, even though its an extra request it means the html/php page will be smaller. Also, it is my understanding once the Javascript is cached it won't be requested again whereas the html/php page will be requested every time.
Depending on your javascript functionality you could also add the async="true" to the script include to ensure the page is downloaded first then the javascript.
Include it externally (your first option). Then when you're doing javascript maintenance, you're not doing it inside PHP as well.
Including the raw text is preferred if you do not expect the page loads per user to go much beyond 1. If you expect your users to request your page multiple times, then the external, cacheable include is the right option. This is usually the case.
Echo the script include so that the javascript in in an external file and then the browser's cache can do it's job.
I was recently visiting a site and noticed that the page had a section that said it noticed that I was using AdBlocking software and could I kindly turn it off to help support a small site like that.
I was just wondering how you would do that? Would it be best done client-side or server-side?
This is something that simply can't be done server side - there's zilch reason for person to knock on your door and say "Look at me, I have AdblockPlus!". When on the client side, adblock is actively trying to influence the page content, which is something you can see happen and see that they are using an adblocker.
Anyway, I happened to know that newgrounds.com is doing this too. (their new layout was screwed up for adblock plus users - as a response they made a contest for the best "if you're not going to help us through our ads, go and buy something in the store"-banner.
A quick look in the source of newgrounds told me they are doing this with some simple javascript.
First in the document:
var user_is_leecher = true;
Next there is a external script tag: src=checkabp?thisistotrickabp=***adress of ad affilliate***
Now the joke: they simply trust adblock plus to filter that script out, as all that's in there is: user_is_leecher = false;
From there, they can do just about anything.
All off the methods mentioned here rely on the ad blockers to strip out code. This doesn't work for some adblockers(like NetBarrier on Mac). You also have to keep updating your code when the adblockers catch on.
To detect if the user is blocking ads, all you have to do is find a function in the ad javascript and try testing for it. It doesn't matter what method they're using to block the ad. Here's what it looks like for Google Adsense ads:
if(typeof(window.google_render_ad)=="undefined")
{
//They're blocking ads, do something else.
}
This method is outlined here: http://www.metamorphosite.com/detect-web-popup-blocker-software-adblock-spam
You could do it on server side by pairing requests for html pages and for the acording ads (probably with some unique identifiers to each request ...) ... But this is just an idea, i've never tried it and never even seen it used.
I found this part in the code which seems to look like how they did it:
/*MOOTOOLS*/
window.addEvent('domready', function(){
$$('.cat-item').each(function(el) {
var fx = new Fx.Morph(el,{ duration:300, link:'cancel' });
el.addEvents({
'mouseenter': function() { fx.start({ 'padding-left': 25 }); },
'mouseleave': function() { fx.start({ 'padding-left': 15 }); }
});
});
if ($$(".google-sense468")[0] && $$(".google-sense468")[0].clientHeight == 0 && $('block-warning')) $('block-warning').setStyle('display','block');
});
/*MOOTOOLS END*/
I guess there are several ways of doing it, but probably the easiest one would be to have some kind of background image, or text, that will be replaced when the ad is loaded. Thus, if the ad gets loaded, you see the ad. If the ad doesn't load, you see the text.
This example would be client side, done by either JavaScript or just plain CSS might even suffice.
There might be some server-side gimmicks that could do this too, but they would be unnecessarily elaborate and clunky. One method that springs to mind would include some kind of API with the advertiser that could be asked "did the user from IP such.and.such load any images?" and in that way get the answer. But I doubt there's such services - it would be much easier to do on the client side.
I believe that is much easier to do it on client side than in server side. Ad blockers are installed on the client, so they can manipulate DOM and block ajax requests. That's why I believe it makes more sense to detect on the client than on the server.
Anyway, this is a standalone simple plugin that detects users with ad blockers enabled, it's open-source and the full code is on github:
https://github.com/retargetly/mockingbird
It's more publisher oriented so they can easily show messages on the ads containers or in a popup. The plugin is frequently updated, and it's worth a try. This is the fiddle also:
http://jsfiddle.net/retargetly/9vsha32h/
The only method you need to use is
mockingbird.adsBlocked(Obj)
The call can be done anywhere in the code and you don't need jQuery to make it work.
Wish you luck !
I don't think there is an easy way to do this. What you can do is to create "trap". Make a php script listen to a very obvious url like yourdomain.com/ad.png. You can probably achieve this by url rewriting. If this page is loaded you can note this in a session variable and send back a 1x1 blank png.
On the next request you can see whether ad.png has been loaded. If it hasn't you can guess that the client is using some form of AdBlock software. Make sure you set the appropriate http headers to prevent clients from caching "ad.png".
This is the only server side approach I can think of at the moment and it has some flaws.
The png file can be cached regardless of the http headers
This will not work for the first http request
Some extra server load as browsers will keep hitting ad.png for each request
That the image gets loaded from the server is no guarantee for it actually being displayed
Probably more side effects that I haven't thought of
Please make a comment on this post if you decide to try it out.
Regarding a client side solution. This shouldn't be to difficult. You can create a tiny Javascript to run on page load complete. This script can check that the page contains the dom-nodes holding the ads. If you this when the page is loaded completely (not only the dom) you can check the width and height of your ad images. The most obvious drawback with this solution is that clients can disable javascripts.
A few good answers here, so I'll just add this:
use some ad management system (You can write Your own). With that, track every ad that's being displayed (and make it obvious, like ads.php or showad.php or whatever). If that script is never called, the user is using SOME form of ad blocking software.
Be sure to handle each and every ad through that handler, though. Mod_Rewrite isn't required, it can be done using simple PHP.
What you can do to detect the adblocker on the server-side is somithing like:
<?php
header('Content-Type: application/javascript');
//Save it to session
session_start();
$_SESSION['noAdblocker']=true;
?>
noAdblocker=true;
Save this file as ads.php
Now the index.php:
<?php
session_start();
$_SESSION['noAdblocker']=false;
?>
<!DOCTYPE HTML><html><head>
<!-- Now place the "ad-script" -->
<script src="ads.php"></script>
</head><body></body></html>
You can add javascript-code to your page, that is only executed if there's no adblocker, e.g. use "ad" as variable-name, use "ad.js" as file-name.
This code sends an ajax-event to the server, saying "this user doesn't use an adlocker". So if you don't receive that event, you know, that this user is blocking ads or even javascript altogether.
I would like to load/refresh a particular page for every 10 secs to view updated data's fetched from Database.
I used META for doing it
<META HTTP-EQUIV=Refresh CONTENT='10; URL=livedata.php'>
But still i agree we also do this by
using :
Javascript to load a div by settimeout
Ajax dynamic refresh
Would be great if you share the performance issues using META , AJAX dynamic refreshing , Javascript settimeout .. Also share the best way of doing it.
Note : Need to refresh whole page rather than specific frame or div.
Using AJAX is the least intruisive to the user, because the user doesn't notice that something is being refreshed/reloaded until it is complete.
Please note that AJAX can perform better or worse than META depending on the situation:
If the data to be updated is small with respect to the full HTML page size, AJAX is better than META, because with AJAX you can send only the data difference, and/or you can send data in more compact format than HTML.
Running JavaScript puts a burden to the user's browser. If the user has 20 tabs open (which is not uncommon), and each of them runs some setTimeout in the background, it can make a huge difference in browser respoinsiveness to convert all of them to JavaScript-free refresh.
If you plan on refreshing the entire page, using <META> tags is the cleanest way. It just seems awkward to have a JS timer refreshing your page when you have a fully-supported HTML-only way of doing this.
However, if you just need a specific part of the page refreshed, use AJAX. It's better in terms of user experience, as well as performance.
using javascript to fetch dynamic content has one more benefit: if the content doesn't load for one time, it can still keep trying. if you reload the whole page and it doesn't load, then it would stop there.
also if you use Ajax, then the display is nicer because you don't see the whole page blanking out and re-rendering again and again.
For the client, there's really no difference between all the methods you mentioned. The only difference I can find is that using doesn't require javascript, like other solutions do, but nowadays everybody has javascript anyway.
The big difference, to me, is in the server usage. If you have 100 users refreshing every 10 seconds, that's already about 10 reqs/sec. Depending on the logic you have to generate the page (which is likely dinamic), this may cause the server usage to skyrocket. Make sure you're careful about that.
note that you can also use header() in PHP to accomplish what the meta tag is doing too. Just make sure you make the header() call before other output.
With jQuery you can do it):
var seconds = 10;
var id = setInterval(function()
{
$('#container').load('whatever.php');
}, 1000*seconds);
:)