Posts by Ekta Bhargava

AJAX in Java

AJAX in Java

Comment Form Example using AJAX in Java In this example, we are creating a form to post comment. The form...

Java AJAX Email Finder Example

Java AJAX Email Finder Example

We can create an AJAX example in Java which checks whether the given email id exists in the database or...

Ajax Java

Ajax Java

We are interacting with the database. You don’t have to make any extra effort. Only write the database logic in...

AJAX Tutorial

AJAX Tutorial

AJAX tutorial covers concepts and examples of AJAX technology for beginners and professionals. AJAX is an acronym for Asynchronous JavaScript and...

Java OOPs Concepts

Java OOPs Concepts

In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm that provides many concepts...

exception_hierarchy

Java – Top 5 Exception Handling Coding Practices to Avoid

The best coding practices related with Java exception handling that you may want to watch out for while doing coding...

Adding and Leveraging a CDN on Your Website

Adding and Leveraging a CDN on Your Website

If you’ve been working around web development for a while, you’ll know that the web has a need for speed. The truth is simple: speed matters and faster is considered better. One "easy win" for increasing performance is using a CDN. We’ve discussed this several times at CSS-Tricks. It's easy in that you aren't rewriting a codebase or hand-editing content, but it's an area of performance many of us might overlook because, well, hosting, servers and cPanels, oh my! Thankfully, the process for integrating a CDN does not have to be hard. Ideally, you get things configured and then things like Google PageSpeed shriek with glee in the form of high performance scores which, in turn, yield to better search engine rankings, higher revenue, a raise for you and...you get the point. This post is going to walk through the process for setting up a CDN to work on a custom web application, followed by some tricks we can use to get the most out of our work. Like I said, it doesn't have to be hard, so let's dive in and make the web faster! It's worth noting that setting up a CDN can be even simpler than what we're covering here for those working with a CMS like WordPress, where plugins can help with the lift. We're going to assume that not everyone has that luxury (shout out to web applications!) and proceed in the more traditional way. Hold up, you lost me at CDN It doesn't hurt for us to review the basic concepts of what a CDN is and what they're used for, so let's start with that. A CDN works by fetching static assets from your site's server and caching them on their servers. When a browser makes a request to visit your site, the static contents are served via the CDN rather than by your site. This is faster because the CDN servers are globally distributed and serve as proxies that determine which server is located physically closest to your visitor, thus delivering content on a speedier, more convenient network. Hence the full name: Content Delivery Network. A Content Delivery Network is globally distributed for optimized delivery of static assets So, how does the browser know to get the resources from the CDN instead of your server? The URL of your static resources are replaced to point to the CDN server instead of the URL of your own site. For example, say we want CDN to be configured as a subdomain. For CSS-Tricks, that might be something like cdn.css-tricks.com and that will be the relative URL for which we base all our assets. Put more succinctly put, the URLs of assets on our site like this: http://www.css-tricks.com/image.jpg http://www.css-tricks.com/style.css http://www.css-tricks.com/script.js ...would become: http://cdn.css-tricks.com/image.jpg http://cdn.css-tricks.com/style.css http://cdn.css-tricks.com/script.js The browser sends the requests to your CDN rather than your server, taking the load off your server and making your whole site faster as a result. Wait, two servers for one site? Yes, to a degree, but it doesn't really mean that you're managing two servers. What we're talking about instead is using the CDN as a virtual layer that stands between your server and a user's browser. That virtual layer listens in on the request the browser is making to your server and gladly responds with cached assets on behalf of the server. In some cases, you may upload your asset directly to the CDN and take the entire burden off your server. What we'll be looking at in this post instead is a process where the CDN fetches assets from your server and pre-caches them so there's no need to upload to different servers and manage multiple locations. How to implement a CDN on a Custom Application Two of the most widely used CDN services are Amazon AWS and MaxCDN, though plenty of other services are certainly available. We'll be focusing most of our attention on MaxCDN as an example of how to set things up. Step 1: Choose a CDN and Register Your Site Once you’ve decided that a CDN is the way to go for your web application, you’ll want to register for an account. There are many, many options out there and, rather than weigh the pros and cons of each (which might make a good future post), here are a few to get you started: MaxCDN AWS CloudFront Cloudflare Akamai Google CLoud Microsoft Azure A common step when registering your account is to set up a pull zone or distribution. A pull zone or distribution is used by the CDN as a bucket for your everyday support files. It will automatically pull the data from a location that you specify upon the first request for the file. The files are served to the end user from either a subdomain of your CDN of choice or a custom domain (sub domain) of your choice that points to the CDN. The data in the bucket is automatically purged from the server after a customizable amount of time. Step 2: Create your CDN URL Your CDN URL is the URL all of your assets will point to once things have been set up. A good rule of thumb is to use a URL name that is easy to do a search and replace in your database for all of your existing URLs. Like any other subdomain, this will need to be set up as a CNAME record in your host's DNS settings. A typical cPanel screen for configuring CNAME records with a host Step 3: Point Your Assets to the CDN Let's look at a method for creating a variable for the CDN URL and how it can be used to help programmatically prepend the URL to our static resources. The reason we want to do this is that (1) it makes it tougher to make mistakes in our markup and (2) it is easier to maintain the URL should we need to change it. We’ll do this is by defining a global CDN variable, then prepend this variable to our static resources URL. We define this variable at both the PHP level and the JavaScript level so that we have more flexibility in how we use it down the road. It also makes it easier for us if we decide to ditch the CDN because all we have to do is replace the variable with a simple / to get things back to the relative path of our original server. Note that the following examples are here to serve illustrate examples rather than to be used literally. Your actual usage may vary. <?php define('cdnURL', 'http://cdn.css-tricks.com/'); ?> <html> <head> <title>Hello World!</> <script type='text/javascript'> /* Let’s define a javascript global for using the CDN inside scripts */ var cdnURL = '<?php echo cdnURL ?>'; </script> <link rel='stylesheet' href='<?php echo cdnURL ?>css/style.css' /> </head> <body> <img src='<?php echo cdnURL ?>img/logo.png' /> <button>Submit</button> <script type='text/javascript' src='<?php echo cdnURL ?>js/main.js'></script> </body> </html> Or, done in JavaScript: (function() { var preloadImage = document.createElement('img'); preloadImage.src = cdnURL + 'img/logo.png'; })(); This does require a slight change in your thought processes as a developer. Every static resource needs to get the cdnURL variable prepended to it. Same thinking goes for your CSS. For example, we can also setup a global CDN variable and prepend it to our CSS resources using a CSS preprocessor, like LESS: @cdnURL: 'http://cdn.css-tricks.com/'; button { background-image: url('@{cdnURL}img/button.png'); &:hover { background-image: url('@{cdnURL}img/button_hover.png'); } } ...or Sass for that matter: $cdnURL: 'http://cdn.css-tricks.com/'; button { background-image: url('@{cdnURL}img/button.png'); &:hover { background-image: url('@{cdnURL}img/button_hover.png'); } } The great thing about this is that you can switch off your CDN by simply setting the cdnURL to / which will recreate all of your relative URLs. This also has the advantage that should you want to switch the CDN URL, you just need to change the cdnURL. That is really the three-step process for setting up a CDN, linking it to your server and then pointing your existing assets to it for so the CDN can serve things up when requested. Let's talk about some advanced settings Setting up the CDN wasn't that scary, right? Now that we've gotten past the main hurdles, we can have some fun with advanced settings that optimize the way our assets are served. TimeToLive (TTL) CDNs typically have a TimeToLive (TTL) set for assets. This is a fancy way of telling the CDN how long (in seconds) before it should treat an asset as stale. At that point, it looks it up on the server again for a "fresh" copy. The longer the TTL, the longer a "version" of that asset will stay with the CDN and continue to be served. The shorter the TTL, the more often it ditches the "version" of the asset it stores and goes back to the original server to look for an updated version. MaxCDN cache settings screen for setting TTL expirations Invalidating assets The double-edged sword with TTL is that you can update an asset on your server and the change will not reflect on your site until the TTL has expired and the CDN makes its next stop to the server to find a new copy. We can overcome this by invalidating an asset. The trick here is to change the filename on update. If the filename changes, the CDN doesn't know any better and reads the newly named file as a completely new asset rather than an update to the existing one. In other words, this: http://cdn.css-tricks.com/image100.jpg ...would be renamed to something like this: http://cdn.css-tricks.com/image101.jpg So long old version and hello new one! Leveraging TTL for version control Hey, so if the CDN is holding onto one version of an asset and there is a fresh copy of it living on our server that it hasn't fetched yet, then we technically have two iterations of the same asset. We can use this to create a form of "version control" where updating our assets on the server doesn't mean we automatically lose them and can revert to a past copy, if needed. The really complicated way to do this is to rename all of your resources every time you make a change like we did when invalidating the asset. However, this is overkill from a maintenance perspective, even if we had to create a variable to do this like we did for the cdnURL. We’re going to do some cheating instead because that's how we roll on a blog that is built around tricks. We'll start by placing our static assets into their own folders so that this: http://cdn.css-tricks.com/image.jpg ...becomes this: http://cdn.css-tricks.com/img100/image.jpg To invalidate the file and force the CDN to serve the latest version, we would modify the subdirectory path like this: http://cdn.css-tricks.com/img101/image.jpg See the difference? The filename stays the same but it now appears to live in a directory on the server. Again, the CDN does not know the difference and sees this as a completely new file. We just created a faux form of version control that happens directly in the folder! But wait, we can do better. Changing the number on a folder on every update is still a cumbersome process and yet another step in the maintenance of our site. What we can do instead is make a few small changes to the site's .htaccess file to do the heavy lifting for us. We'll outsmart the CDN by serving all our assets from the same folder, but make it look like it’s being served from a versioned folder, thanks to some rewrite rules. <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^ver-[0-9]+.[0-9]+.[0-9]+(.*)$ $1 [L,NC] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php?/$1 [QSA,L] </IfModule> Ha! Now our server is spoofing the version number in the URL while delivering our example image.jpg asset from the same path on the server where it was originally uploaded. Invalidating all assets on demand The last thing to round this out is to integrate our version control trick into our HTML markup so that the CDN will refresh all of the assets as soon as we want to fully invalidate them. We'll set up a config file where we define a variable for the version number, import that variable into our asset URL structure and then change the version number each time we want to push a refresh of our assets across the board. Here's what that might look like in a PHP config file: VERSION 1.0.0 Configure::load('cdn'); define('VERSION', file_get_contents(APP.DS."Config".DS."VERSION")); define('CDN', Configure::read('CDN.path').VERSION.'/'); /* the trailing slash is important */ Here's how that might work as a LESS config file: @VERSION: '1.0.0'; @import 'cdn'; @import 'version'; @CDNURL: '@{CDN}@{VERSION}/'; button { background-image: url('@{CDNURL}img/button.png'); &:hover { background-image: url('@{CDNURL}img/button_hover.png'); } } As you can see, you can also choose to use the CDN variable as a file, environment variable or whatever would work best for you. The principles are mostly the same, all will achieve the desired end result of incorporating the CDN URL (and version number) into all of our external resources. CDN, FTW! Hopefully this takes the scare out of setting up a CDN. It can certainly appear to be a daunting task and there absolutely are advanced settings that can get you lost in the weeds. The initial setup is what most of us need anyway and the benefits are profound when it comes to performance and user experience, among a host of other things (pun intended). The truth is that it gets even simpler if you manage content on your site with a popular CMS like WordPress, where there are plugins galore to streamline the process even further. Even if we do not have the luxury of plugins, setting up a CDN can still be pretty straightforward, even for the least hosting-oriented of us. The setup is the largest hurdle and we were able to break that down into three basic steps. All else flows nicely from there. Adding and Leveraging a CDN on Your Website is a post from CSS-Tricks

Lazy Loading Responsive Adsense Ads

Lazy Loading Responsive Adsense Ads

You've been hard at work optimizing your site. You've already done things like lazy-loading Google Maps and been wondering if there was anything else you could do. For example, is there anything we can do to improve the loading of ads? Good news, there is some things you can do. You can respect user's mobile data plan by loading ads only when they are likely to appear in the viewport zone. You can also serve ads in the right size in accordance to the screen of the device. That would be nice of you. That would not only be responsive but also responsible. The Problem The nature of Google Adsense is that the ads, along with the script, file are loaded automatically: this may unreasonably slow down the appearance of the other important things, like styles, fonts, or other scripts. Google Adsense: no lazy load Moreover, the correct ad size is determined only once right before the ad load. It means that if the user resizes the browser or rotates the tablet, the ad size remains the same and most likely doesn't fit the context anymore. Google Adsense: not responsive The Arguments There are many factors that Google Adsense considers for monetization, but "Click Through Rate" plays the major role in revenue. Therefore, focusing on clicks rather than just views in a long term may result in increased revenue. You can get more clicks by making your site look and feel trustworthy to a user. You can get that trust by prioritizing which parts of your website to load first. Serving ads first instead of the actual content that the user came for is a way to the decreasing ad clicks and impressions. Logically, Google Adsense shouldn't track an ad view when the ad never gets into the zone of the viewport. I don't know if Google Adsense has this kind of tracking yet, but since the technology is JavaScript-based, they have all the means to do it. It is typical for smartphone and tablet users to constantly switch between portrait and landscape modes until they find the most comfortable one. Providing the most appropriate ad size for each mode improves the possibility of getting more clicks. When loading ads via Ajax, you just only need to serve the correct markup. The plugin takes care of the rest. See the next section! The Solution I've made a JavaScript plugin to help. It helps to lazy loads the ads: Google Adsense: with lazy load No matter where the ad is, above or below the viewport, it won't get loaded if the ad is out of view. It also helps to resize the ads: Google Adsense: responsive The banner gets reloaded at a particular breakpoints. JavaScript The plugin itself is a tiny piece of JavaScript code, and I made two versions of it: vanilla and jQuery. I called it adsenseLoader. You can grab the files here: adsenseloader.js; no dependencies (IE 9+).1.1KB when minified and gzipped. jquery.adsenseloader.js; jQuery dependency.835 bytes when minified and gzipped. This is how you initialize it: // vanilla var instance = new adsenseLoader( '.adsense' ); // accepted argument types: Selector String, Element, NodeList, Array // jQuery $( '.adsense' ).adsenseLoader(); You can also customze it. The default options are: var options = { laziness: 1, /* @int (<=0) This sets the laziness of loading the ads: (viewport height) * laziness . For example: 0 – ad load starts when at the least a tiny part of it gets in the viewport; 1 – ad load starts when the distance between the ad and the viewport is no more than the height of the viewport; 2 – 2x viewports, etc. */ onLoad: false /* @bool A callback function which is fired when the ad is fully loaded. A single argument (object) of the ad element is passed. For example: onLoad: function( ad ) { alert( ad.getAttribute( 'data-ad-slot' ) + ' ad is loaded' ); } */ }; // vanilla var instance = new adsenseLoader( '.adsense', options ); // jQuery $( '.adsense' ).adsenseLoader( options ); Moreover, there's a methodical function destroy, which does as it's named: destroys the ad and brings back the corresponding DOM fragment to the default state. You can call the function for the whole instance as well as for single elements: // vanilla var instance = new adsenseLoader( '.adsense', options ); instace.destroy(); // or document.querySelectorAll( '.adsense' )[ 0 ].adsenseLoader( 'destroy' ); // jQuery $( '.adsense' ).adsenseLoader( options ); $( '.adsense' ).adsenseLoader( 'destroy' ); // or $( '.adsense' ).get( 0 ).adsenseLoader( 'destroy' ); Lastly, you can change a few more options that have a global impact across all of the plugin instances. You can call the function anywhere, but it's designed to be used before creating any instance of the plugin. The default options are: var options = { scriptUrl: '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', /* @string (url) URL for Google Adsense's executive script file */ throttle: 250 /* @int (miliseconds) This defines how often the plugin should make calculations during the processes such as resize of a browser's window or viewport scroll. 250 means that this happens 4 times in a second. */ }; // vanilla adsenseLoaderConfig( options ); // jQuery $.adsenseLoaderConfig( options ); HTML Here we have to simplify Adsense code snippet by leaving only two parameters and put it all into a container element: <div class="adsense"> <ins data-ad-client="ca-pub-4676533344420647" data-ad-slot="5741144487"></ins> </div> CSS This part is responsible for controlling the size of ads. Using CSS, we will define the width and the height of the container element with the exact dimensions for the expected ad. With the help of media queries and a pseudo element, we'll set the guides for the plugin which will later be able to determine when to resize/reload an ad. .adsense { width: 970px; height: 90px; display: block; } .adsense:before { display: none !important; } .adsense ins { width: 100%; height: 100%; display: block; } @media screen and ( max-width: 1024px ) { .adsense { width: 728px; height: 90px; } .adsense:before { content: '1024'; } } @media screen and ( max-width: 800px ) { .adsense { width: 468px; height: 60px; } .adsense:before { content: '800'; } } /* etc. */ Luckily, Adsense itself is able to pick the right banner size according to the given dimensions. The width and height properties for selector .adsense determine what ad we will be expecting. Using media queries and the pseudo element :before, we tell the plugin when it is supposed to reload the ad. The JavaScript part checks for differences for content values. An ad is automatically reloaded when a difference is detected. You can use any different integers across the media queries. In my examples, I equated the values to the media queries' width parameters for an easier maintenance. Resizing the banners is a job split across two disciplines: CSS is the logic and JavaScript is the execution. Demo Remember that if you're using an ad blocker that blocks AdSense, you may not see this work correctly. See the Pen Lazy-Loading Responsive Adsense Ads by Osvaldas (@osvaldas) on CodePen. You are welcome to follow and contribute to the project on GitHub. Disposing Multiple Ads Here's a quick tip on how to manage multiple differently sized ads. Say we have two banners: one in the content area and another in the sidebar. We can assign different class names for each: <div class="adsense adsense--main">...</div> <div class="adsense adsense--side">...</div> Now we can define common styles for .adsense and individual styles for .adsense--main and .adsense--sidebar, like this: .adsense{ display: block; } .adsense:before { display: none !important; } .adsense ins { width: 100%; height: 100%; display: block; } .adsense--main { width: 728px; height: 90px; } .adsense--side { width: 336px; height: 280px; } @media screen and ( max-width: 1024px ){ .adsense--main { width: 468px; height: 60px; } .adsense--main:before { content: '1024'; } } @media screen and ( max-width: 800px ){ .adsense--side { width: 250px; height: 250px; } .adsense--side:before { content: '800'; } } Ad Loading Indication or Taking Advantage of onLoad() You can indicate the loading process in a few ways: provide a placeholder image, add text, border, background or anything else that best meets your design direction and is visible until the ad loads: Google Adsense Loading Indication Preview To start with, let's add extra an HTML element and some styling, which basically adds an overlay with text “Loading…” above the ad: <div class="adsense"> <p class="adsense__loading">Loading…</p> </div> .adsense { position: relative; } .adsense__loading { width: 100%; height: 100%; background-color: rgba( 255, 255, 255, .9 ); display: table; /* for vertical centering */ position: absolute; top: 0; left: 0; } .adsense--loaded .adsense__loading { display: none; } .adsense__loading span { text-align: center; vertical-align: middle; /* for vertical centering */ display: table-cell; /* for vertical centering */ } Google Adsense Loading Indication Stack Using the callback function onLoad() we can add the class adsense--loaded which is responsible for hiding the .adsense__loading element: // vanilla var instance = new adsenseLoader( '.adsense', { onLoad: function( ad ) { if( ad.classList ) ad.classList.add( 'adsense--loaded' ); // IE 10+ else ad.className += ' ' + 'adsense--loaded'; // IE 8-9 } }); // jQuery $( '.adsense' ).adsenseLoader( { onLoad: function( $ad ) { $ad.addClass( 'adsense--loaded' ) } }); Google Adsense Loading Indication Animated Stack Thanks for reading and being a responsible web designer/developer. Lazy Loading Responsive Adsense Ads is a post from CSS-Tricks

Bliki: AliasingBug

Bliki: AliasingBug

Aliasing occurs when the same memory location is accessed through more than one reference. Often this is a good thing, but frequently it occurs in an unexpected way, which leads to confusing bugs. Here's a simple example of the bug. Date retirementDate = new Date(Date.parse("Tue 1 Nov 2016")); // this means we need a retirement party Date partyDate = retirementDate; // but that date is a Tuesday, let's party on the weekend partyDate.setDate(5); assertEquals(new Date(Date.parse("Sat 5 Nov 2016")), retirementDate); // oops, now I have to work three more days :-( What's happening here is that when we do the assignment, the partyDate variable is assigned a reference to the same object that the retirement data refers to. If I then alter the internals of that object (with setDate) then both variables are updated, since they refer to the same thing. Although aliasing is a problem in that example, in other contexts it's what I expect. Person me = new Person("Martin"); me.setPhoneNumber("1234"); Person articleAuthor = me; me.setPhoneNumber("999"); assertEquals("999", articleAuthor.getPhoneNumber()); It's common to want to share records like this, and then if it changes, it changes for all references. This is why it's useful to think of reference objects, which we deliberately share [1], and Value Objects that we don't want this kind of shared update behavior. A good way to avoid shared updates of value objects is to make value objects immutable. Functional languages, of course, prefer everything to be immutable. So if we want changes to be shared, we need to handle that as the exception rather than the rule. Immutability is a handy property, one that makes it harder to create several kinds of bugs. But when things do need to change, immutability can introduce complexity, so it's by no means a free breakfast. Acknowledgements Graham Brooks and James Birnie's comments on our internal mailing list led me to write this post. Further Reading The term aliasing bug has been around for a while. It appears in Eric Raymond's Jargon file in the context of the C language where the raw memory accesses make it even more unpleasant. Notes 1: The Evans Classification has the notion of Entity, which I see as a common form of reference object. Share: if you found this article useful, please share it. I appreciate the feedback and encouragement

FormLinter

FormLinter

I absolutely love this idea from Thoughtbot. Just like automated tools that check your HTML for syntax, formatting, validity, or whatever else, FormLinter checks your <form> HTML for best practices. Things like every input having a label, using correct input types, required fields, and more. Ben Orenstein: Doing all these things right is worth the effort: improvements like these improve accessibility and increase conversions. However, checking this sort of thing by hand is tedious and error-prone. We were testing some forms in the ol' CSS-Tricks team chat and it was doing what it said on the box. On Geoff's personal site, it gave his contact form a "B" for not having matching labels for inputs and not having any fields required (seems like a fairly high grade?). The form was output from the mega-popular "Contact Form 7" for WordPress, also a bit surprising. Many of the forms we tested bombed the app though. No word on that. Might be an HTTPS thing? Direct Link to Article — Permalink FormLinter is a post from CSS-Tricks