Javascript

A few notes when writing javascript in pagespeed optimization

document.write

Never use function document.write to append html on document, use the jQuery function instead $('body').append

Event

see all javascript event in bellow

//ready document
_HWIO.docReady(function(){});
//all js in page ready include jquery
_HWIO.readyjs(function(){ });
//window ready event
_HWIO.winReady(function(){ });
//wait for exist `jQuery` object
_HWIO.waitForExist(function(){
jQuery('.woocommerce-product-gallery').css('opacity','');
}, ['jQuery']/*, 500,20, 'custom-name'*/);
_HWIO.waitForExist(function(){
//your code
}, function(){
return typeof jQuery!='undefined';
});

Run script with conditional:

//check for exist variable
_HWIO.readyjs(function(){
cookie.set('a',1);
}, ['cookie']);
//run suddenly after this js (handle) has loaded
_HWIO.readyjs('js-cookie',function(){
console.log("~~ ready js-cookie")
});
//execute when user got interactive such as mouse move, click,scroll..
_HWIO.readyjs(null,function(){
_log('@when interactive');
});

To known JS,CSS name (handle) you open chrome dev tool & in tab console, type _HWIO.extra_assets

list of JS & CSS (with key = Handle name)

As you can see above, JS and CSS files have been merged. You can also find the original JS files by adding parameters ?merge_js=0 at the end of the URL. Same for CSS ?merge_css=0

In addition, you may want to specify which JS code will run immediately and delay until the user interacts on the web page.

//combine php hook `hpp_delay_it_script`
_HWIO.add_event('run_script', function(v, js){
//when interactive
if( js.indexOf('ready js-cookie')!==-1)return 0;
return v;
});
</script>
<?php
});

Before executing any Javascript code, there is a core inline JS that is placed at the top of the page. And you will want to append your inline js after it, then use code bellow:

add_action('hpp_print_initjs', function(){
#if(is_home() || is_front_page())
if(isset($GLOBALS['hpp-criticalfile'])) {
?>
_HWIO.add_event('hpp_allow_js', function(v,att){
return att.l.endsWith('.less') || att.l.endsWith('.html') || (location.href.indexOf('merge_js=0')===-1 && (att.l.indexOf('code.jquery.com')!==-1 || att.l.indexOf('jquery.min.js')!==-1))? 0:v;
});
<?php
}
});

the event hpp_allow_js to allow / not allow, decide which JS file should be run or not.