Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

51.

What is the use of localStorage in Html5?

Answer»

HTML5 introduced different approaches for web developers to save persistent content on a user’s machine namely Local Storage, aka Web Storage and WebSQL Storage. Local Storage feature is easy and here is the syntax for storing and retrieving.

<script> localStorage.setItem(“Name”, “Sreekanth”); var firstName = localStorage.getItem(“Name”); </script>

Information is stored as key-value pair and can be easily stored and retrieved using a simple API. Event handlers can also be registered to monitor for changes to localStorage values.  localStorage is well supported in modern browsers and it is consistently supported across desktop and mobile browsers.

The localStorage OBJECT provides much more space than was available with older tools. Modern browsers support a minimum of 5 MB of data, which is substantially more than is allowed through cookies (which are LIMITED to 4 KB each).

If the storage limit is reached, or if the user manually turns off storage capabilities, QuotaExceededError exception is thrown. Below code is to be used to prevent an exception to the user.

try { localStorage.setItem('firstName', $('#firstName').val()); } catch(e) { // degrade gracefully }

Currently, only string values can be stored in web storage, but SOMETIMES we might need to store arrays or JavaScript objects. To accomplish this,  we need to use JavaScript Object Notation (JSON) UTILITY methods.

The following example creates a JSON object and uses the stringify() method to convert the value to a string that can then be PLACED in web storage and use the parse() method to deserialize a new instance of the object from the string representation of the object that was stored

var person = { firstName: sreekanth', lastName: boya' }; localStorage.setItem(‘person', JSON.stringify(person));   var person = JSON.parse(localStorage.getItem(‘person '));

localStorage is designed to retain data across multiple sessions.

52.

How to improve performance by Minify &amp; Compress Files

Answer»

Minification is the act to strip out unnecessary characters from code to reduce the size, and a minifier is the tool that does it. Most often, the term is applied to JavaScript, but as you shall see, the technique can also be used on JavaScript, CSS and HTML.

JavaScript Minification: JavaScript offers the most potential for minification. Aside from removing white spaces and comments, Windows-style line breaks (CRLF) can be converted to UNIX-style breaks (LF), and VARIABLE names can be shortened.

function toggle(elementID) {         if ( document.getElementById(elementID).style.display != 'none’ ) {           document.getElementById(elementID).style.display  = 'none';      } else {            document.getElementById(elementID).style.display = '';       }} function toggle(elementID) {    var el = document.getElementById(elementID);       if ( el.style.display != 'none' ) {                el.style.display = 'none’;     } else {         el.style.display = ''; }}

CSS Minification : Many of the minification techniques outlined for JavaScript minification are also applicable to CSS — the removal of extra whitespaces, removal of comments, and conversion of CRLF to LF.

.MYCLASS {                margin-left: 10px;               margin-right: 10px;            margin-bottom: 20px;            margin-top: 20px;} myclass { margin: 20px 10px;}

Html Minification: Html minification is newer and is still experimental. Following are the available options:

  • Remove comments.
  • Remove comments from JavaScript and CSS blocks.
  • Remove character data (CDATA) blocks from CSS and JavaScript.
  • Collapse whitespace.
  • Collapse boolean attributes (for example, selected="selected").
  • Remove attribute quotes (when it is SAFE to do so).
  • Remove redundant attributes (for example, language="JavaScript").
  • Use short doctype.
  • Remove empty attributes (for example, title="").
  • Remove optional closing tags.
  • Remove empty elements such as <p></p>.
  • Remove type="text/javascript" from INLINE script.

OPTIMIZING IMAGES: Implementing compression on an image with our impacting the quality can reduce the size of the image.  There are different ways to improve the performance of a web page when images are present.

  • Reduce the Image size
  • Eliminating the Http request for favicon instead use Data URI
  • Use Lazy loading
  • Avoid empty src attributes
  • Setting appropriate width and height attributes
53.

How to improve performance by caching Common files

Answer»

Caching generally refers to the storage of web resources (HTML documents, images, and so on) in a temporary location to improve performance. Caches can be implemented by most web browsers, perimeter (intermediate) web proxies, and at the gateways of large INTERNAL networks. Transparent proxies (caches) are used by many Internet Service Providers (ISPs), reverse proxies sit in front of web servers, and the web server itself utilizes caching.

Different types of caching are explained below.

  • Caching by Browsers

Web browsers implement a cache to hold recently and frequently accessed resources. It is much faster to retrieve a resource from the cache than to request it again from the web server. When deciding what to cache, browsers are usually quite well behaved and respect the caching policy dictated by the server.

There are several problems with browser caching. The size of the cache TENDS to be quite small by default and when the cache BECOMES full, the algorithm to decide what to remove is crude. Commonly, the Least Recently Used (LRU) algorithm is used to purge old items.

  • Intermediate Caches:

The intermediate cache/proxy is commonly used by ISPs and larger organizations. When used by ISPs, it typically takes the form of a transparent caching proxy that silently intercepts HTTP traffic. When the client makes a request, the proxy intercepts it and checks its local cache for a copy of the resource. If none is found, it makes the request on the client’s behalf and then relays this back to the client, caching a copy itself in the process. When another client on the same ISP requests the same resource, a cached copy is returned.

Reverse Proxies Browser caches and intermediate proxies are generally for the benefit of the client, reverse proxies are usually used for the benefit of the web server. These proxies sit in front of the web server and have two purposes (although sometimes they are used for just one of these reasons): caching and load balancing. For caching, they can be used to lighten the load on the back-end web server by serving up cached versions of dynamically generated pages (thus cutting CPU USAGE). For load balancing, they can be used for load-balancing multiple back-end web servers.

Below are the different ways to control the cache.

  • Controlling Caching
  • Conditional GETs: Send a conditional GET request, the request knows if a local, cached copy of a resource is still valid.  The “If-Modified-Since header” is SENT in the request. If the server determines that the resource has been modified since the date given in this header, the resource is returned as normal. Otherwise, a 304 Not Modified status is returned.
  • Utilizing Cache-Control and Expires Headers: Apart from “If-Modified-Since header”, there are two more headers that can control caching: Expires and Cache-Control: max-age. These headers effectively say to the client, “This resource expires on such-and-such a date. Until then, use your locally cached copy (if you have one).” The result is that the client doesn’t need to issue a conditional GET.
    • ExpiresByType image/gif "access plus 2 months“
    • ExpiresByType image/jpeg "access plus 2 months“
54.

How to caption an image

Answer»

Rewrite the following code to apply the caption “This is an image of something interesting’

<IMG src="path/to/image" alt="About image" /&GT; <p>Image of Mars. </p>

There is no easy or SEMANTIC way to associate the caption, WRAPPED in a paragraph tag, with the image element itself.  Using HTML5 <figure> element along with <figcaption> element, we can now semantically associate captions with their image counterparts.

Example

<figure>    <img src="path/to/image" alt="About image" />    <figcaption>        <p>This is an image of something interesting. </p>    </figcaption> </figure>

Output

55.

What are the phantom nodes? How can it be resolved?

Answer»

While grouping headings resulted in problems with the outline of a document; this problem is called phantom nodes.  To avoid the phantom nodes, use <hgroup> to group two or more headings (h1, h2, h3 ,h4, h5, and h6).

<hgroup></hgroup> is a CONTAINER for two or more headings (h1, h2, h3 ,h4, h5, and h6). It INDICATES that the headings are closely related, so it will be used to group together headings with subheadings, titles, and subtitles.  Using <hgroup> avoids phantom nodes problem because it combines the two headings into one node. The <hgroup> tags can only contain headings.

The following is an example:

Example

<!DOCTYPE html> <html>     <head>           <meta CHARSET ="UTF-8">           <title>Images</title>     <style type="text/css">        h1 { font-size:160%; font-weight:bold; margin-top:5px; margin-bottom:0; }        h2 { font-size:130%; font-weight:bold; margin-top:0; margin-bottom:5px; }        article { width:445px; text-align:left;  }     </head>     <body>          <article> <hgroup> <h1>I PUT our holiday DATES and address on a social network</h1>                <h2>An idiot's tale</h2>  </hgroup> <p>We returned to a ransacked house, even the furniture was taken.<br> Your friend, <br>Sreekanth</p>           </article>     <body> </html>

Output

56.

What is the difference between article vs section? Provide usage examples.

Answer»

<SECTION> is best used as a sub-section of an <article> and should always contain and enclose a heading, something like the following:

  • Don’t use <section> as a target for styling or SCRIPTING; use a <div> for that
  • Don’t use <section> if <article>, <aside>, or <nav> is more appropriate.
  • Don’t use <section> unless there is NATURALLY a heading at the start of the section.
<article> <h1>A heading, any level from h1 to h6</h1> <section>   <h1>A heading, any level from h1 to h6</h1>some content </section> <section> <h1>A heading, any level from h1 to h6</h1>some content </section>  </article> 

An <article> is a stand-alone ITEM, such as a self-contained piece of information that could be LIFTED from the page and published in a forum, magazine, RSS feed, or newspaper. It should contain and enclose a heading (h1 to h6) and it can contain two or more sections. The key words are STAND ALONE.

57.

Write code to demonstrate the scenarios Anchor Tags/ Hyperlinks

Answer»

The Web is based on hyperlinks. Each Web page contains active links to other pages, which in turn link to even more pages, until presumably the entire Web (or at least a great chunk of it) is bound together. In fact, that’s where the name “web” comes from. Hyperlinks can connect to other places on a Web page, to other pages within the Web site, to pages outside the site, and to many types of Web and non-Web content.

  • Scenario 1: Hyperlinking to a Web Page.

The syntax for a hyperlink starts with <a> tag and uses an href=attribute which provides the URL or path to a destination.

E.g <a href="http://www.microsoft.com">

This is followed by the text that will appear underlined as the link text that user click, or by a reference to the image that will serve as a hyperlink

E.g Visit <a href="http://www.microsoft.com">Microsoft.com</a> for the latest information.
  • Scenario 2: USING Partial Paths and Filenames

In order to link to a specific page, the complete file name should be specified. Example, To provide a direct link to the page where users can download Windows Media Player, it should have the following tag:

<a href="http://www.microsoft.com/windows/windowsmedia/player/download/download.aspx">Download Windows Media Player</a>
  • Scenario 3: Using Relative and Absolute Paths

Paths that contain a complete address that anyone can use to get to that page are called absolute paths. Absolute paths are very RELIABLE, but they are also long and awkward to type.

E.g <a href="http://www.microsoft.com/articles/Windows10.htm">Windows 10</a>

Instead of providing the full path only the destination file is provided, it is called a relative path. Below are the relative path examples.

<a href=" Windows10.htm">Windows 10</a> <a href=“articles/ Windows10.htm">Windows 10</a>
  • Scenario 4: Setting a Target Window

To direct the hyperlink to open a page in a new window, add the attribute target=″_blank″ to the <a> tag. For example, to open the foliage.htm file in a new window, the tag would be structured like this:

<a href=" Windows10.htm " target="_blank">Windows10</a>
  • Scenario 5: Hyperlinking to an E-Mail Address

Hyperlinks can point not only to web pages but also to email address. Email hyperlinks are useful to send a message to a particular person directly.

<a href="mailto:support@microsoft.com">Contact Us</a>
  • Scenario 6: Creating and Hyperlinking to Anchors

An anchor is a marker within an HTML document, roughly analogous to a bookmark in a Word document. Define a specific location in the document with an anchor name, and then hyperlink directly to that anchor. Anchors are most valuable in long documents with multiple sections. They provide a means for users to jump directly to whatever section they want rather than having to read or scroll through the entire document.  

E.g

<div id="top">conclusion </div>     <a href="#conclusion">View the Conclusion</a> # plays a critical for identifying the section
58.

How to detect whether a browser supports a particular feature using the Modernizr library. 

Answer»

Modernizr is an open source, MIT-licensed JavaScript library that DETECTS SUPPORT for many HTML5 & CSS3 features. You should ALWAYS use the latest version. To use it, include the following highlighted <script> element at the top of your PAGE.

<!DOCTYPE html> <html> <HEAD>  <meta charset="utf-8">  <title>Dive Into HTML5</title>   <script src="modernizr.min.js"></script> </head> <body></body> </html>

Following are the Apis supported by Modernizr

  • Modernizr.canvas attribute is used to detect support for the canvas API. 
  • Modernizr.canvastext attribute is used to detect support for the canvas text API.
  • Modernizr.video attribute is used to detect support for HTML5 video. 
  • Modernizr.localstorage attribute is used to detect support for HTML5 local storage. 
  • Modernizr.webworkers attribute is used to detect support for web workers.
  • Modernizr.applicationcache is used to detect support for offline web applications.
  • Modernizr.geolocation is used to detect support for the geolocation API.
59.

What are the new input types provided by HTML5 for forms?

Answer»

HTML5 introduces more than a dozen new input TYPES for forms. The new input types provide dual benefits

  • Less development time
  • Improved user experience.   

Below are the new input types and it’s usage.

  • Search: Search is the most COMMON action perform on the web every day. Search is not only for Google, Bing, or Yahoo, but it can be a field on e-commerce site we make a purchase from on the web, on Wikipedia, and even on a personal blog. The syntax for Search is
<input type="search" name="search">
  • Email:  Email input type is no different from a standard text input type but it allows one or more e-mail addresses to be entered with the REQUIRED attribute. The browser looks for patterns to ensure a valid e-mail address has been entered. The syntax for Email is
<input type="email" name="email" required>

The URL input type is for web addresses.  The browser will carry out simple validation and present an error message on form submission. This is likely to include looking for forward slashes, periods, and spaces and possibly detecting a valid top-level domain (such as .com or .co.uk).  It also supports multiple addresses. The syntax for Url is

<input type="url" name="url" required>
  • Tel: tel does not have any particular syntax enforced. Phone numbers differ around the world, making it difficult to guarantee any type of specific notation except for allowing only numbers and perhaps a + symbol to be entered.  Validation against specific phone number format can be done using client-side validation. The syntax for tel is
<input type="tel" name="tel" id="tel" required>
  • Number: Number is used for specifying a numerical value. It, Safari, and Chrome, number input is rendered as a spinbox control whereby the user can click the arrows to move up or down or enter directly into the field. Firefox, on the other hand, renders the field like a standard text box. Support for type="number" will be in IE 10 also.  With the additional attributes min, max, and step, we can change the default step value of this spinbox control as well as set minimum, maximum, and starting values (using the standard HTML value attribute). The syntax for number is
<input type="number" min="5" max="18" step="0.5" value="9" name="shoe-size" >
  • Range: The Range input type is similar to number but more specific. It represents a numerical value within a given range. In OPERA, Safari, and Chrome, type="range" renders as a slider. The syntax for range is
<input id="skill" type="range" min="1" max="100" value="0">
  • Date: HTML5 provides date control which provides a date picker functionality with is INTEGRATED with the browser without any external libraries.  Date control allows to select a single date; select a week, month, time, date and time, and even date and time with a time zone using the different input types. The markup is pretty straightforward. The syntax for Date is
<input id="dob" name="dob" type="date">

Also, using the min and max attributes to ensure the user can only choose from a specified date range.

<input id="startdate" name="startdate" min="2012-01-01" max="2013-01-01" type="date">
  • Month: Month is used to select a particular month on the web page. It can be used for a credit card expiry date. The syntax for month is
<input id="expiry" name="expiry" type="month" required>
  • Week: week is used to select a particular week in a month. The syntax for week is
<input id="vacation" name="vacation" type="week">
  • time : time renders a spinbox for selecting the precise time. The syntax for time is
<input id="exit-time" name="exit-time" type="time">
  • DateTime: We can combine the date and time by using type="datetime" for specifying a precise time on a given day. The syntax for datetime is
<input id="entry-day-time" name="entry-day-time" type="datetime">
  • Datetime-local: Using datetime-local, user can select a precise time on a given day with a local time zone variation. The syntax for datetime-local is
<input id="arrival-time" name="arrival-time " type="datetime-local">
  • Color: The Color input type allows the user to select a color and returns the hex value for that color. It is anticipated that users will either be able to type the value or select from a color picker,. The syntax for color is
<input id="color" name="color" type="color">
60.

What Is Html5? Explain the new features

Answer»

HTML5 has been developed considering current and future browser development and past, present, and future web development work. Due to this, HTML5 gained significant momentum. Driven by practicality, it has emerged as the W3C’s choice for accelerated development.

HTML5 is backward compatible and it contains all the features of the HTML4 spec, though with a few changes and improvements. It also contains additional capabilities for BUILDING dynamic web APPLICATIONS and creating higher quality markup.

Features of HTML5

  • New Semantic elements to allow us to define more parts of our markup unambiguously and semantically rather than using lots of classes and IDs.
  • APIs for adding video, audio, scriptable graphics, and other rich application type content to our sites.
  • HTML5 has been deliberately built to compete with proprietary plug-ins such as FLASH and Silverlight.
  • New features for standardizing functionality that we already built in bespoke, hacky ways. Server-sent updates and form validation spring to mind immediately.
  • Microdata: Microdata allows machine-readable data to be embedded in HTML documents so that browsers and search engines can extract data from the page.  
  • Web Workers: Allows a JavaScript operation to work in the background without interfering with the user’s browsing.
  • Web Storage: This is a more powerful form of a cookie. It can store a large amount of data on the client side. It can store up to 5MB of data, whereas a cookie is limited to about 4KB.
  • Web Sockets: Allows pages to use the WebSocket protocol to send two-way messages between a browser and a server.
  • Cross-document and channel messaging: Cross-document messaging provides a capability to exchange documents regardless of the source domain and without enabling cross-site attacks. Channel messaging uses independent pieces of code blocks to communicate directly.
  • Server sent events: Using this feature, push notifications can be sent from a server to a client browser as DOM events.
  • New features to plug gaps in the functionality we traditionally had available in OPEN standards, such as defining how browsers should handle markup errors, allowing web apps to work offline, allowing us to use always-open socket connections for app data TRANSFER, and again, audio, video and scriptable images (canvas).