Lazy Loading PHP-JavaScript

From HaFrWiki42
Jump to navigation Jump to search

Normally when a user opens a webpage, the entire page’s contents are downloaded and rendered in a single go [1].
While this allows the browser to cache the web page, there’s no guarantee that the user will actually view all of the downloaded content.

For example, If an entire photo gallery is downloaded but the user leaves after only viewing the first image, then the result is wasted memory and bandwidth.

Instead of bulk loading all of the content when the page is accessed, content can be loaded when the user accesses a part of the page that requires it.
With lazy loading, pages are created with placeholder content which is only replaced with actual content when the user needs it.

Benefits of Lazy Loading

  1. Lazy loading strikes a balance between optimizing content delivery and streamlining the end user’s experience.
  2. Users connect to content faster, since only a portion of the website needs to be downloaded when a user first opens it.
  3. Businesses see higher customer retention as content is continuously fed to the user, reducing the chances the user will leave the website.
  4. Businesses see lower resource costs since content is only delivered when the user needs it, rather than all at once.

Adding lazy loading can make a website load faster, save bandwidth, and provide a truly uninterrupted browsing session.
Almost half of all users who visit a website view only a single page.
By continuously adding new content as the user scrolls, lazy loading can make that single view really count.

The Lazy-Loading technique can be used for images, forms and (javascript)-coding.
All three are straight-forward, serach the internet and you will find several examples how to do that.
The PHP-embedded method however is - as far as I have seen - never documented.

Requirements

  • Webserver Apache
  • jQuery
  • Server side PHP with at least 3 PHP-Files
    • The startup PHP-code in 'Project.php' which creates the client-website
    • The backend PHP-code in 'Project-be.php'.
    • The common PHP-code with all common variables defined in 'Project-co.php'

Assuming

The website has

  • Menu structure with tabs (Bootstrap navbar)
  • Tabs have names like 'tabHome', 'tabHelp' etc. In this case assumed the tab 'tabPrefs'.


Client PHP

The jQuery .ready is somewhere is your code. <syntaxhighlight lang="javascript" line highlight="1,16,18"> var jsPrefs = false;

$(document).ready(

 function() {
     'use strict';
     ...
     /**
      * Detecting the change of tab.
      * The target contains the name of the tab
      * @param  event e The event
      * See http://ericsaupe.com/tag/bootstrap-3-tabs-example-ajax
      */
     $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var target = $(e.target).attr("href") // activated tab
        switch(target) {
          case '#tabPrefs'        :   
                   if (jsPrefs == false) {
                         lazyLoadingJS4PHP( 'js/Prefs-JS.php', 'doGetFormPrefs()' );
                   }
                   break;
          ...
      }
 }

); </syntaxhighlight>

  • 1. The variable 'jsPrefs' has to be defined before naking any call to the lazy code.
  • 16. The tab-name.
  • 18. The loaded script has to set the jsPrefs variable to true. The 2 parameters are:
    • The name of the PHP-Javascript file. The file contains the javascript for handling the form.
    • The callback function to be executed after the loading of the script. The callback function loads the form and does that afyer the Javascript is injected.

Common PHP

The constants and defines in the following code fragment are: <syntaxhighlight lang="PHP" highlight="23" start='1' line > /* -- Preferences are individual for the project, therefor only a few are defined. ---------------------------------------

*/

const PREFS_GUILANG = "prefsGuiLang"; const PREFS_USER_ID = "prefsUserId"; const PREFS_GEN_ID = "prefsGenId"; const PREFS_GEN_ACCESSTOKEN = "prefsAccessToken"; const PREFS_GEN_FONT_FAMILY = "prefsGenFontFamily"; const PREFS_GEN_BACKGROUND = "prefsGenBackground"; const PREFS_GEN_RESULTSPAGE = "prefsGenNumRows"; const PREFS_GEN_SEARCHDELAY = "prefsGenSearchDelay"; const PREFS_GEN_SEARCHCHARS = "prefsGenSearchChars"; const PREFS_GEN_BUT_UPDATE = "prefsGenButUpdate";

/* -- Ajax Calls to the backend ------------------------------------------------------------------------------------------

*/

define ('ajaxForm4PrefsGen' , 'ajaxForm4PrefsGen' ); // Project-bf.php define ('ajaxPrefsGenUpdate' , 'ajaxPrefsGenUpdate' ); // Project-bf.php define ('ajaxGetJS4PHP' , 'ajaxGetJS4PHP' ); // Project-be.php

... require_once( common_inc . '/phpinclude/Util.php' ); ... </syntaxHighlight>

  • 23. Gets the utility class (is an example on how to do that). Please note the variable 'common_inc' which has to be set previous to execute this line.

BackEnd PHP

The backend has to render the PHP in PHP-Javascript file. It does so by: <syntaxhighlight lang="php" line highlight="1,3,5"> require_once 'Project-co.php;

$action = Util::getPostValue('action');

if ($action === ajaxGetJS4PHP) {

  $phpFile = Util::getPostValue( 'phpfile' );
  ob_start();
  include $phpFile;
  $content = ob_get_contents();
  ob_end_clean();
  echo $content;
  die();

} </syntaxhighlight>

  • 1. Gets the common constants and defines. Also for the helper classes such as Util.php.
  • 3. The function 'Util::getPostValue' is an utility helper class method.
  • 5. Defined in the common-file.
  • 7. Turn on output buffering
  • 8. Gets the PHP-Javascript file.
  • 9. Renders the PHP and gets the Javascript only (PHP has been removed). Return the contents of the output buffer
  • 10. Clean (erase) the output buffer and turn off output buffering.
  • 11. Makes the script available through AJAX.

PHP-Javascript File

Showing 2 methods of using the lazy call:

  • JS-File
  • PHP-Js-File

<syntaxhighlight lang="javascript" line> /**

* Gets javascript file on-demand (or lazy-loading).
* Is only possible for a JS-file, not a PHP-file with JS inside!
* @param  string scriptFile Existing full name of the JavaScript file.
*/

function lazyLoadingJS( scriptFile ) {

  'use strict';
  var jslC ;
  var head = document.getElementsByTagName('head')[0];
  jslC = document.createElement("script");
  jslC.type = "text/javascript";
  jslC.src  = scriptText;
  head.appendChild( jslC );

} // lazyLoadingJS

/**

* Gets javascript code on-demand (or lazyloading).
* The file has to be a PHP-File with the Javacode embedded.
* @param  string phpFile    Existing full name of the PHP-JavaScript file.
* @param  string cbFunction Name of the callback function ( i.e. 'xxx() )
*/

function lazyLoadingJS4PHP( phpFile, cbFunction ) {

  $.ajax({
     url       : '@@Project@@-be.php',
     async     : true,
     type      : "POST",
     data      : {
       action    : "<?php echo ajaxGetJS4PHP; ?>",
       phpfile   : phpFile,
     },
     datatype  : 'script',
  })
  .done( function( scriptText) {
     $('head').append( scriptText);
     setTimeout( cbFunction, 50) ;
  })
  .fail( function( jqXHR, status, errorThrown) {
     httpStatusResponse = jqXHR.status;
     logts( sprintf(logFormatLBW, met, "AJAX", "Fail, HTTP Reason: " + httpStatusResponse));
  });

} // lazyLoadingJS4PHP </syntaxhighlight>



See also

top

Reference

top

  1. Blog StackPath, What's Lazy-Loading