Sunday 1 May 2016

How Google AMP Speeds Up Performance


Source : https://www.ampproject.org/docs/get_started/technical_overview.html

The following optimizations combined are the reason AMP pages are so fast they appear to load instantly:

Allow only asynchronous scripts
JavaScript is powerful, it can modify just about every aspect of the page, but it can also block DOM construction and delay page rendering (see also Adding interactivity with JavaScript). To keep JavaScript from delaying page rendering, AMP allows only asynchronous JavaScript.
AMP pages can’t include any author-written JavaScript. Instead of using JavaScript, interactive page features are handled in custom AMP elements. The custom AMP elements may have JavaScript under the hood, but they’re carefully designed to make sure they don’t cause performance degradation.
While third-party JS is allowed in iframes, it cannot block rendering. For example, if third-party JS uses the super-bad-for-performance document.write API, it does not block rendering the main page.

Size all resources statically

External resources such as images, ads or iframes must state their size in the HTML so that AMP can determine each element’s size and position before resources are downloaded. AMP loads the layout of the page without waiting for any resources to download.
AMP uncouples document layout from resource layout. Only one HTTP request is needed to layout the entire doc (+fonts). Since AMP is optimized to avoid expensive style recalculations and layouts in the browser, there won’t be any re-layout when resources load.

Don’t let extension mechanisms block rendering

AMP doesn’t let extension mechanisms block page rendering. AMP supports extensions for things like lightboxesinstagram embedstweets, etc. While these require additional HTTP requests, those requests do not block page layout and rendering.
Any page that uses a custom script must tell the AMP system that it will eventually have a custom tag. For example, the amp-iframe script tells the system that there will be an amp-iframe tag. AMP creates the iframe box before it even knows what it will include:
<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>

Keep all third-party JavaScript out of the critical path

Third-party JS likes to use synchronous JS loading. They also like to document.write more sync scripts. For example, if you have five ads on your page, and each of them cause three synchronous loads, each with a 1 second latency connection, you’re in 18 seconds of load time just for JS loading.
AMP pages allow third-party JavaScript but only in sandboxed iframes. By restricting them to iframes, they can’t block the execution of the main page. Even if they trigger multiple style re-calculations, their tiny iframes have very little DOM.
The time it takes to do style-recalculations and layouts are restricted by DOM size, so the iframe recalculations are very fast compared to a recalculating styles and layout for the page.

All CSS must be inline and size-bound

CSS blocks all rendering, it blocks page load, and it tends to get bloated. In AMP HTML pages, only inline styles are allowed. This removes 1 or often more HTTP requests from the critical rendering path compared to most web pages.
Also, the inline style sheet has a maximum size of 50 kilobytes. While this size is big enough for very sophisticated pages, it still requires the page author to practice good CSS hygiene.

Font triggering must be efficient

Web fonts are super large, so web font optimization is crucial to performance. On a typical page that has a few sync scripts and a few external style sheets, the browser waits and waits to start downloading these huge fonts until all this happens.
The AMP system declares zero HTTP requests until fonts start downloading. This is only possible because all JS in AMP has the async attribute and only inline style sheets are allowed; there’s no HTTP requests blocking the browser from downloading fonts.

Minimize style recalculations

Each time you measure something, it triggers style recalculations which are expensive because the browser has to layout the entire page. In AMP pages, all DOM reads happen first before all the writes. This ensures there’s the max of one recalc of styles per frame.
Learn more about impact of style and layout recalculations on rendering performance.

Only run GPU-accelerated animations

The only way to have fast optimizations is to run them on the GPU. GPU knows about layers, it knows how to perform some things on these layers, it can move them, it can fade them, but it can’t update the page layout; it will hand that task over to the browser, and that’s not good.
The rules for animation-related CSS ensure that animations can be GPU-accelerated. Specifically, AMP only allows animating and transitioning on transform and opacity so that page layout isn’t required. Learn more about using transform and opacity for animation changes.

Prioritize resource loading

AMP controls all resource downloads: it prioritizes resource loading, loading only what’s needed, and prefetches lazy-loaded resources.
When AMP downloads resources, it optimizes downloads so that the currently most important resources are downloaded first. Images and ads are only downloaded if they are likely to be seen by the user, above the fold, or if the user is likely to quickly scroll to them.
AMP also prefetches lazy-loaded resources. Resources are loaded as late as possible, but prefetched as early as possible. That way things load very fast but CPU is only used when resources are actually shown to users.

Load pages in an instant

The new preconnect API is used heavily to ensure HTTP requests are as fast as possible when they are made. With this, a page can be rendered before the user explicitly states they’d like to navigate to it; the page might already be available by the time the user actually selects it, leading to instant loading.
While prerendering can be applied to all web content, it can also use up a lot of bandwidth and CPU. AMP is optimized to reduce both of these factors. Prerendering only downloads resources above the fold and prerendering doesn’t render things that might be expensive in terms of CPU.
When AMP documents get prerendered for instant loading, only resources above the fold are actually downloaded. When AMP documents get prerendered for instant loading, resources that might use a lot of CPU (like third-party iframes) do not get downloaded.

What is AMP and How AMP Works

AMP HTML :zap:

Official Website : https://www.ampproject.org

AMP HTML is a way to build web pages for static content that render with reliable, fast performance. It is our attempt at fixing what many perceive as painfully slow page load times – especially when reading content on the mobile web.
AMP HTML is entirely built on existing web technologies. It achieves reliable performance by restricting some parts of HTML, CSS and JavaScript. These restrictions are enforced with a validator that ships with AMP HTML. To make up for those limitations AMP HTML defines a set of custom elements for rich content beyond basic HTML. Learn more about how AMP speeds up performance.

How does AMP HTML work?

AMP HTML works by including the AMP JS library and adding a bit of boilerplate to a web page, so that it meets the AMP HTML Specification. The simplest AMP HTML file looks like this:
<!doctype html>
<html ⚡>
  <head>
    <meta charset="utf-8">
    <link rel="canonical" href="hello-world.html" >
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
    <script async src="https://cdn.ampproject.org/v0.js"></script>
  </head>
  <body>Hello World!</body>
</html>
This allows the AMP library to include:
  • The AMP JS library, that manages the loading of external resources to ensure a fast rendering of the page.
  • An AMP validator that provides a way for web developers to easily validate that their code meets the AMP HTML specification.
  • Some custom elements, called AMP HTML components, which make common patterns easy to implement in a performant way.

The AMP JS library

The AMP JS library provides builtin AMP Components, manages the loading of external resources, and ensures a reliably fast time-to-paint.

The AMP Validator

The AMP Validator allows a web developer to easily identify if the web page doesn't meet the AMP HTML specification.
Adding "#development=1" to the URL of the page instructs the AMP Runtime to run a series of assertions confirming the page's markup meets the AMP HTML Specification. Validation errors are logged to the browser's console when the page is rendered, allowing web developers to easily see how complex changes in web code might impact performance and user experience.
It also allows apps that integrate web content to validate the web page against the specification. This allows an app to make sure the page is fast and mobile-friendly, as pages adhering to the AMP HTML specification are reliably fast.
Learn more about validating your AMP pages.

AMP HTML Components

AMP HTML Components are a series of extended custom elements that supplement or replace functionality of core HTML5 elements to allow the runtime to ensure it is solely responsible for loading external assets and to provide for shared best practices in implementation.
See our docs and reference for more info.

Releases

We push a new release of AMP to all AMP pages every week on Thursday. The more detailed schedule is as follows:
  • Every Thursday we cut a green release from our master branch.
  • This is then pushed to users of AMP who opted into the AMP Dev Channel.
  • On Monday we check error rates for opt-in users and bug reports and if everything looks fine, we push this new release to 1% of AMP pages.
  • We then continue to monitor error rates and bug reports throughout the week.
  • On Thursday the "Dev Channel" release from last Thursday is then pushed to all users.
You can always follow the current release state of AMP on our releases page. The release used by most users is marked asLatest release and the current Dev Channel release is marked as Pre-release.

AMP Dev Channel

AMP Dev Channel is a way to opt a browser into using a newer version of the AMP JS libraries.
This release may be less stable and it may contain features not available to all users. Opt into this option if you'd like to help test new versions of AMP, report bugs or build documents that require a new feature that is not yet available to everyone.
Opting into Dev Channel is great to:
  • test and play with new features not yet available to all users.
  • use in Q&A to ensure that your site is compatible with the next version of AMP.
If you find an issue that appears to only occur in the Dev Channel version of AMP, please file an issue with a description of the problem. Please always include a URL to a page that reproduces the issue.
To opt your browser into the AMP Dev Channel, go to the AMP experiments page and activate the "AMP Dev Channel" experiment. Please subscribe to our low-volume announcements mailing list to get notified about important/breaking changes about AMP.

Further Reading

If you are creating AMP pages, check out the docs on ampproject.org.
These docs are public and open-source: https://github.com/ampproject/docs/. See something that's missing from the docs, or that could be worded better? Create an issue and we will do our best to respond quickly.
Resources:
Reference:
Technical Specifications:

Who makes AMP HTML?

AMP HTML is made by the AMP Project, and is licensed under the Apache License, Version 2.0.

Saturday 30 April 2016

Parse Json file In Jquery Ajax


See Running Demo Here -Demo For Parsing Json File In Jquery


Json File Data

 [
    {
        "alignment1": "TM"
    },
    {
        "alignment2": "TLBR"
    },
    {
        "alignment3": "BL"
    },
    {
        "ruleTimer": "6"
    },
    {
        "music": "Enable"
    },
    {
        "rule1": "Rule 1"
    },
    {
        "rule2": "Rule 2"
    },
    {
        "rule3": "Rule 3"
    },
    {
        "rule4": "Rule 4"
    },
    {
        "ID1": "p7ZsBPK656s"
    },
    {
        "name1": "Disfigure - Blank [NCS Release]"
    },
    {
        "ID2": "__CRWE-L45k"
    },
    {
        "name2": "Electro-Light - Symbolism [NCS Release]"
    },
    {
        "ID3": "J2X5mJ3HDYE"
    },
    {
        "name3": "DEAF KEV - Invincible [NCS Release]"
    },
    {
        "color1": ""
    },
    {
        "color2": ""
    },
    {
        "color3": ""
    },
    {
        "color4": ""
    },
    {
        "color5": ""
    }

]


Index.html Code 

 <!doctype html>
<html>
<head>

    <title>How to Parse a JSON file using jQuery</title>
   
    <style>
        body{
            text-align: center;
            font-family: arial;
        }

        .button{
            margin:20px;
            font-size:16px;
            font-weight: bold;
            padding:5px 10px;
        }
    </style>


</head>
<body>
    <a href="data.json" target="_blank">Open JSON file</a><br />
    <input type="button" value="Get and parse JSON" class="button" />
    <br />
    <span id="results"></span>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

    <script>

        //When DOM loaded we attach click event to button
        $(document).ready(function() {
           
            //after button is clicked we download the data
            $('.button').click(function(){

                //start ajax request
                $.ajax({
                    url: "data.json",
                    //force to handle it as text
                    dataType: "text",
                    success: function(data) {
                       
                        //data downloaded so we call parseJSON function
                        //and pass downloaded data
                        var json = $.parseJSON(data);
                        //now json variable contains data in json format
                        //let's display a few itemscons
                        console.log("data is - "+json);
                       
                       // $.each(json, function(idx, obj) {

//$.each(obj, function(idx, obj) {
//console.log("one-"+obj+" "+idx);
//$('#results').append("<strong>"+obj+"</strong> :- "+idx+"<br/><br/>");
//});
//});


function Iterate(data)
{
    jQuery.each(data, function (index, value) {
        if (typeof value == 'object') {
            //alert("Object " + index);
            Iterate(value);
        }
        else {
             alert(index + "   :   " + value);
             $('#results').append("<strong>"+index+"</strong> :- "+value+"<br/><br/>");
        }
    });

};

Iterate(json);
                       
                      //  $('#results').html('Plugin name: ' + json.alignment1);
                    }
                });
            });
        });
    </script>

</body>

</html>

Parse Json file In Jquery Ajax With Object Under Object


See Running Demo Here -Demo For Parsing Json File In Jquery


Json File Data

 [
    {
        "alignment1": "TM"
    },
    {
        "alignment2": "TLBR"
    },
    {
        "alignment3": "BL"
    },
    {
        "ruleTimer": "6"
    },
    {
        "music": "Enable"
    },
    {
        "rule1": "Rule 1"
    },
    {
        "rule2": "Rule 2"
    },
    {
        "rule3": "Rule 3"
    },
    {
        "rule4": "Rule 4"
    },
    {
        "ID1": "p7ZsBPK656s"
    },
    {
        "name1": "Disfigure - Blank [NCS Release]"
    },
    {
        "ID2": "__CRWE-L45k"
    },
    {
        "name2": "Electro-Light - Symbolism [NCS Release]"
    },
    {
        "ID3": "J2X5mJ3HDYE"
    },
    {
        "name3": "DEAF KEV - Invincible [NCS Release]"
    },
    {
        "color1": ""
    },
    {
        "color2": ""
    },
    {
        "color3": ""
    },
    {
        "color4": ""
    },
    {
        "color5": ""
    }

]


Index.html Code 

 <!doctype html>
<html>
<head>

    <title>How to Parse a JSON file using jQuery</title>
    
    <style>
        body{
            text-align: center;
            font-family: arial;
        }

        .button{
            margin:20px;
            font-size:16px;
            font-weight: bold;
            padding:5px 10px;
        }
    </style>


</head>
<body>
    <a href="data.json" target="_blank">Open JSON file</a><br />
    <input type="button" value="Get and parse JSON" class="button" />
    <br />
    <span id="results"></span>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

    <script>

        //When DOM loaded we attach click event to button
        $(document).ready(function() {
            
            //after button is clicked we download the data
            $('.button').click(function(){

                //start ajax request
                $.ajax({
                    url: "data.json",
                    //force to handle it as text
                    dataType: "text",
                    success: function(data) {
                        
                        //data downloaded so we call parseJSON function 
                        //and pass downloaded data
                        var json = $.parseJSON(data);
                        //now json variable contains data in json format
                        //let's display a few itemscons
                        console.log("data is - "+json);
                        
                       // $.each(json, function(idx, obj) {

//$.each(obj, function(idx, obj) {
//console.log("one-"+obj+" "+idx);
//$('#results').append("<strong>"+obj+"</strong> :- "+idx+"<br/><br/>");
//});
//});


function Iterate(data)
{
    jQuery.each(data, function (index, value) {
        if (typeof value == 'object') {
            //alert("Object " + index);
            Iterate(value);
        }
        else {
             alert(index + "   :   " + value);
             $('#results').append("<strong>"+index+"</strong> :- "+value+"<br/><br/>");
        }
    });

};

Iterate(json);
                        
                      //  $('#results').html('Plugin name: ' + json.alignment1);
                    }
                });
            });
        });
    </script>

</body>

</html>

How To Read Json File Into Javascript Arrray



Contacts.json File 


{
    "ppl1":{
        "Name":"Jhon",
        "Surname":"Kenneth",
        "mobile":329129293,
        "email":"jhon@gmail.com"
    },
    "ppl2":{
        "Name":"Thor",
        "Surname":"zvalk",
        "mobile":349229293,
        "email":"thor@gmail.com"
    },
    "ppl3":{
        "Name":"Mila",
        "Surname":"Kvuls",
        "mobile":329121293,
        "email":"mila@gmail.com"
    }
}

Read / Parse Json File into Javascript Array


Use The Code Below To Read Json File ( Contacts.json  ) . File Data Shown Above into Javascript Array

$.getJSON('contacts.json', function (json) {
var array = [];
for (var key in json) {
    if (json.hasOwnProperty(key)) {
        var item = json[key];
        array.push({
            name: item.Name,
            surname: item.Surname,
            mobile: item.mobile,
            email: item.email
        });            
    }
}
});
Here getJSON will make a ajax request to contacts.json file and file contents is shown above in the post . Ajax request will get json data from the file and output that data to 'json' object . In code i am making an empty array then opening a for loop through the json object that contains data that ajax request has read from contacts.json file then we are pushing data from json object to newly created array
 That way we will be having data in new created Javascript array from json file

Thursday 28 April 2016

Codeigniter open_basedir_restriction in effect



Error :

Message: mkdir(): open_basedir restriction in effect. File() is not within the allowed path(s): (/home/thelazyppl/:/home/thelazyppl:/tmp:/usr/local/lib/php/)

Filename: drivers/Session_files_drivers.php

Details About Error :

CodeIgniter installation is trying to save its session files to somewhere that is unwritable .  I would like to recommend you store sessions in database . You need to do this settings in config.php file Under Application -> Config Folder in Your CodeIgniter Project Default Structure

In My Case I was using CodeIgniter3 Version . You Can Use The Below User Guide Link To Make Configurations Required For Solving this error properly 

User Guide For CodeIgniter 3 :User Guide CodeIgniter3 Open_basedir_restriction in effect

Sure Short Solution For CodeIgniter 3 :- 


  • Navigate to your project folder - Under Application folder in Codeigniter go Under Config Folder
  • Then Open Config.php file Search For below line of code$config['sess_save_path'] = NULL;
  • And Replace this line of code with line of code below -
    $
    config['sess_save_path'] = '/tmp';


The better option would be to use the database driver, for which the details are just below that.
If you were having these issues on CodeIgniter 2, you would need definitely need to enable the database. To do this you would change the $config['sess_use_database'] option to TRUE and then run the SQL shown in the CodeIgniter 2 user guide.

Tuesday 26 April 2016

How To Use Progress Bar With Ajax Request Jquery


Use The Code Below To Have Progress Bar with %age Complete For Fetching Data

Preview Of Jquery Ajax Loader
HTML CODE 

<div id="progressbar">
    <div class="progress-label">Loading...</div>

</div>

CSS CODE

.progress-label {
    float: left;
    margin-left: 50%;
    margin-top: 5px;
    font-weight: bold;
    text-shadow: 1px 1px 0 #fff;

}

Javascript / Jquery Code

  $(function () {
      var progressbar = $("#progressbar"),
          progressLabel = $(".progress-label");

      progressbar.progressbar({
          value: false,
          change: function () {
              progressLabel.text(progressbar.progressbar("value") + "%");
          },
          complete: function () {
              progressLabel.text("Complete!");
          }
      });

      function progress() {
          var val = progressbar.progressbar("value") || 0;

          progressbar.progressbar("value", val + 1);

          if (val < 99) {
              setTimeout(progress, 100);
          }
      }

      setTimeout(progress, 3000);

  });

Thursday 14 April 2016

Convert Json Array To Table Format in AngularJS


The Following Code will Split Json Array Into Tabulated Format with Rows

HTML CODE

<div id="div1">
</div>

CSS CODE

#mytable,td{
    border:1px solid blue;
}

Javascript Code

var obj=[
    {
        id : "001",
        name : "apple",
        category : "fruit",
        color : "red"
    },
    {
        id : "002",
        name : "melon",
        category : "fruit",
        color : "green"
    },
    {
        id : "003",
        name : "banana",
        category : "fruit",
        color : "yellow"
    }
]
var tbl=$("<table/>").attr("id","mytable");
$("#div1").append(tbl);
for(var i=0;i<obj.length;i++)
{
    var tr="<tr>";
    var td1="<td>"+obj[i]["id"]+"</td>";
    var td2="<td>"+obj[i]["name"]+"</td>";
    var td3="<td>"+obj[i]["color"]+"</td></tr>";
 
   $("#mytable").append(tr+td1+td2+td3);

}

Output Image


Friday 4 March 2016

How To Fix Call to undefined function apache_get_modules()



Fatal error:  Call to undefined function apache_get_modules() in
apache_get_modules() is only available when the PHP is installed as a module and not as a CGI. This is the reason why you cannot use this function and suffering from the error . The other reason would be caused by the disable_functions directive in your php.ini . you can use the following written php code to check whether rewrite module is enabled or not in your case while using CGI server API

<?php
if (is_mod_rewrite_enabled()) {
  print "The apache module mod_rewrite is enabled.<br/>\n";
} else {
  print "The apache module mod_rewrite is NOT enabled.<br/>\n";
}

/**
 * Verifies if the mod_rewrite module is enabled
 *
 * @return boolean True if the module is enabled.
 */
function is_mod_rewrite_enabled() {
  if ($_SERVER['HTTP_MOD_REWRITE'] == 'On') {
    return TRUE;
  } else {
    return FALSE;
  }
}
?>

To Check whether you are running Php Under CGI or Apache you can use procedure below
Create a check_phpinfo.php file and Write PHP Code Written Below -
<?php

// Show all information, defaults to INFO_ALL
phpinfo();

?>
Then the file and Navigate to Url like - www.example.com/check_phpinfo.php and It will show you php file in server
In Four line you can see "Server API CGI/FastCGI" That Denotes you are using PHP under CGI / Fast CGI