Jump to content
Latest News: (loading..)
bruyndoncx

improving performance by optimizing javascript loading

Recommended Posts

I'm working on improving the site speed and i'm playing around with head.js to do this.

 

The following article nicely summarizes different options

http://www.netmagazine.com/features/essential-javascript-top-five-script-loaders

 

Is a particular loader script foreseen in 2.3.4, or 2.4 releases ?

 

If possible, I try to stick to oscommerce standards, would be silly if I pick one, and oscommerce picks another one ...


KEEP CALM AND CARRY ON

I do not use the responsive bootstrap version since i coded my responsive version earlier, but i have bought every 28d of code package to support burts effort and keep this forum alive (albeit more like on life support).

So if you are still here ? What are you waiting for ?!

 

Find the most frequent unique errors to fix:

grep "PHP" php_error_log.txt | sed "s/^.* PHP/PHP/g" |grep "line" |sort | uniq -c | sort -r > counterrors.txt

Share this post


Link to post
Share on other sites

It's something that needs to be looked at.

Could you share your code changes with head.js ?

 

 

 


This is a signature that appears on all my posts.  
IF YOU MAKE A POST REQUESTING HELP...please state the exact version
of osCommerce that you are using. THANKS

 
Get the latest current code (community-supported responsive 2.3.4.1BS Edge) here

 

Share this post


Link to post
Share on other sites

Using head.js is a 3 part solution

 

1) add head.js as first script in your head, in the template_top file

<!DOCTYPE html>
<html class="no-js">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/headjs/0.99/head.min.js"></script>

 

2) add the scripts to the template_bottom file to load after your main body content.

use shortcodes to abbreviate scripts, and use these shortcodes to spell out the script dependencies

since my site is quite customized, the end of template_bottom currently looks like this. Just to give you and idea of different possibilities

</div> <!-- bodyWrapper //-->
<?php
 echo $oscTemplate->getBlocks('footer_scripts');
?>
   <script>
  head.js({jquery:"ext/jquery/jquery-1.8.0.min.js"});
  head.ready("jquery",function(){
    head.js({jqueryui:"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"}, function() {
		  $("#headerShortcuts").buttonset();	     
	    });

    head.js("ext/jquery/jquery.cookie.js");
    head.js("ext/jquery/searches_controller.js", function() {
	  function clearInput(e){
	    if(e.value=='<?php echo TEXT_SEARCH_HERE; ?>')e.value="";
	  }
    });	  
  });

  head.js("font/cufon-yui.js", "font/titallium.js", function () {
	  Cufon.replace('#announcement')('.box-heading') ('.headingBoxCategories') ('h2') ('.headingBoxProductSocialBookmarks') ('.headingalsopurchased') ('.headingBoxProductNotifications') ('h1') ('.left h2') ('#footer h3')('.input.button') ('.top_text2') ('.textbtn') ('#content4 h1') ('#content2 h1') ('#content3 h1')	 ('#indexSubCategoryImage a');
	  Cufon.replace( { hover:true, fontFamily: 'Khmer UI' });
  head.js("ext/jquery/howdydo-bar/jquery.howdydo-bar.js", function () {
	    $( '#announcement' ).howdyDo({
		  action        : 'hover',
		  initState    : 'open',         // initial bar state: 'closed' | 'open'
		  keepState   : true,
		  effect        : 'slide',
		  easing	  : 'easeOutBounce',
		  duration    : 500,
		  //barStyle	 : 'stackoverflow',
		  openAnchor    : '<img src="ext/jquery/howdydo-bar/down.png" border=0 />',
		  closeAnchor    : '<img src="ext/jquery/howdydo-bar/up.png" border=0 />'
	    });
  });

   });
   </script>  
</body>
</html>
<?php
 require(DIR_WS_INCLUDES . 'application_bottom.php');
?>

 

 

3) replace any document.ready calls with

head.ready("jquery", function() { .

...

}

 

There are different ways of structuring your code that is dependent on other libraries being loaded

 

for instance, the fancybox code becomes - note, my css id is a custom call, standard is another id for the gallery

  <link rel="stylesheet" type="text/css" href="ext/jquery/fancybox/jquery.fancybox-1.3.4.css" />
  <script type="text/javascript">
  head.ready("jquery", function() {
    head.js("ext/jquery/fancybox/jquery.fancybox-1.3.4.pack.js", function() {
	  $("a#one_img").fancybox();
    });
  });
  </script>

 

That's it in a nutshell, but evidently small changes will need to be made throughout the site for the javascript calls, making sure they fire off only when the particular library is loaded.


KEEP CALM AND CARRY ON

I do not use the responsive bootstrap version since i coded my responsive version earlier, but i have bought every 28d of code package to support burts effort and keep this forum alive (albeit more like on life support).

So if you are still here ? What are you waiting for ?!

 

Find the most frequent unique errors to fix:

grep "PHP" php_error_log.txt | sed "s/^.* PHP/PHP/g" |grep "line" |sort | uniq -c | sort -r > counterrors.txt

Share this post


Link to post
Share on other sites

Furthermore, on css files

If you want to async load css files, the same kind of call is made, but you must include them in the <head> section

 

I'm not sure if including css this way is better /overall faster or not

I'm just listing the possibility here for completeness

 

Other advanced modernizer stuff

  • responsive design / mediaqueries
  • css routing
  • css3 feature detection

There is a lot more enabled in head.js.

I have not looked into this part, so I have no opinion pro or con about it.

I can see it's potential, but don't know if/how it would be better compared to other solutions for html5 compatibility and responsive design


KEEP CALM AND CARRY ON

I do not use the responsive bootstrap version since i coded my responsive version earlier, but i have bought every 28d of code package to support burts effort and keep this forum alive (albeit more like on life support).

So if you are still here ? What are you waiting for ?!

 

Find the most frequent unique errors to fix:

grep "PHP" php_error_log.txt | sed "s/^.* PHP/PHP/g" |grep "line" |sort | uniq -c | sort -r > counterrors.txt

Share this post


Link to post
Share on other sites

@@bruyndoncx

 

I have head.js implemented on my site. It does shave off some load time (about 5%) on my site. I think it could be useful to load in custom css files like extra fonts but I think I would rather use a a standard <link> for the main stylesheet just to avoid the dreaded flash-of-unstyled-content.

 

I'll have to dig deeper into the css functions of the script and see what I can come up with.


Matt

Share this post


Link to post
Share on other sites

@@bruyndoncx

 

I have head.js implemented on my site. It does shave off some load time (about 5%) on my site. I think it could be useful to load in custom css files like extra fonts but I think I would rather use a a standard <link> for the main stylesheet just to avoid the dreaded flash-of-unstyled-content.

 

I'll have to dig deeper into the css functions of the script and see what I can come up with.

I pretty much came to the same conclusion. I have it running on a second site I'm developing, but not on my main site yet. Good to know you have not encountered any issues, that gives me the courage to continue ;)


KEEP CALM AND CARRY ON

I do not use the responsive bootstrap version since i coded my responsive version earlier, but i have bought every 28d of code package to support burts effort and keep this forum alive (albeit more like on life support).

So if you are still here ? What are you waiting for ?!

 

Find the most frequent unique errors to fix:

grep "PHP" php_error_log.txt | sed "s/^.* PHP/PHP/g" |grep "line" |sort | uniq -c | sort -r > counterrors.txt

Share this post


Link to post
Share on other sites
Posted (edited)

Some Useful Tricks To Improve JavaScript Performance

1. Use document.getElementById()

Using JQuery it becomes quite easy to select DOM elements using tags, classes or ids. But this approach involves several iterations as JQuery loops through DOM elements to find a match. You can speed it up by using document.getElementById()

// Using JQuery
var container = $(“#container”);
// Plain JavaScript
var container = document.getElementById(“container”);

2.Compress your files
Smaller the size of files faster it is to download them for the users, which results in faster performance. Use a compression method such as Gzip or Brotli to reduce the size of your JavaScript files

3.Minify

Minification refers to the removal of unwanted/cumbersome elements from our JavaScript source.

Unwanted refers to comments, semi-colons, whitespace etc. While cumbersome refers to shortening function and variable names, reducing an if-else into ternary etc. It can be achieved with build tools like UglifyJsGoogle Closure compiler or online tools like JS CompressJS minifier etc.

4.Use mouseup instead of click
Users interaction via mouse or keyboard fires several events in a specific order. It is better to bind your functionality with the mouseup event which fires before click event, this can provide performance boost especially in the older browser such as IE. This ensures that none of the interactions are missed if a user makes several mouse clicks in rapidly.

5.Cache as much as possible

Caching your files in browser helps to improve the loading time of the site both for previous visitors as well as for first time users. The browser uses the locally cached copy for any pages loaded after the initial one instead of fetching them over the network. Use JavaScript service workers to cache files for offline use. Going offline gives the application feel of desktop or mobile which gives the illusion of faster app.

6.Favor native functions and constructs
Rather than writing your own algorithms, it’s better to use native functions and constructs. ECMAScript provides lot of native functions like Math.floor() , Math.round()String.prototype.match()and many others.

7. Use async and defer attributes
 async and defer are attributes can be added to script tags to make them either load asynchronously to the page or defer until the page has completely loaded. Using either of these attributes doesn’t block the DOM from rendering, which makes the application faster.

<! — load example.js asynchronously to the page →
<script src=”example.js” async></script>
<! — load example.js after the page has loaded →
<script src=”example.js” defer></script>

8.Recycle the DOM
If you look at Facebook, Instagram, Twitter and other sites that have infinite scrolling enabled then you can understand that more and more elements are getting added to the DOM. These can cause problems since we have to now query more elements. Therefore performance decreases and browser slows down by consuming RAM.

This problem can be solved by recycling DOM elements. Allocate some elements to use for displaying content to the DOM and when that elements exit the viewport, you take it back to the bottom.

9.Switch to HTTP/2

HTTP/2 is the latest version of HTTP protocol that provides some enhancements that will improve not only JavaScript performance but also improve the speed of the site in general. HTTP/2 is multiplexed which means that it handles multiple requests and responses simultaneously.

10.Animate with requestAnimationframe
Animations should ideally render at 60fps(or a frame every 16.667ms) which is just perfect for human eyes. JavaScript libraries like Anime.js and GSAP are helpful for creating quick animations, but if your JavaScript animations are still running slow, try using the requestAnimationFrame() method to get them up to speed. With requestAnimationFrame, we tell the browser to call a function to render a frame.

function moveLeft(){
// code to move the box to the left
}
window.requestAnimationFrame(moveLeft);
Edited by Karen Sloot

Share this post


Link to post
Share on other sites
Posted (edited)

to load JS in the header or footer I recommand put all JS to load in one PHP file In catalog/ext/

create a file named js.php put the follow inside:

$js = array('jquery/jquery-3.3.1.min.js',
	'jquery/ui/jquery-ui-1.12.1.min.js',
	'templates/js/bootstrap.min.js',
	'js/general.js');
						
$mergeJS = "";
foreach ($js as $js_file) { $mergeJS.= file_get_contents($js_file); }
ob_start('ob_gzhandler');
header('Content-type: text/javascript');
header('Vary: Accept-Encoding');
echo ($mergeJS);

than in the catalog/includes/template_top.php load this file with:

<script type="text/javascript" src="ext/js.php"></script>

Its also good for SEO, than its only one file for to load and ofcourse JS should be minimized.

For CSS files can do as well. My site loading speed increased by 40%!!!

Edited by mcmannehan

  • The clever one learn from everything and from everybody
  • The normal one learn from his experience
  • The silly one knows everything better

[socrates, 412 before Christ]

Computers help us with the problems we wouldn't have without them!
99.9% of the bugs sit in front of the computer!
My programmed add-ons: WDW EasyTabs 1.0.3, WDW Facebook Like 1.0.0

if(isset($this) || !isset($this)){ // that's the question...

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×