Javascript
A few notes when writing javascript in pagespeed optimization

document.write

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

Events

See all javascript events below:
1
//ready document
2
_HWIO.docReady(function(){});
3
4
//all js in page ready include jquery
5
_HWIO.readyjs(function(){ });
6
7
//window ready event
8
_HWIO.winReady(function(){ });
9
10
//wait for exist `jQuery` object
11
_HWIO.waitForExist(function(){
12
jQuery('.woocommerce-product-gallery').css('opacity','');
13
}, ['jQuery']/*, 500,20, 'custom-name'*/);
14
15
_HWIO.waitForExist(function(){
16
//your code
17
}, function(){
18
return typeof jQuery!='undefined';
19
});
Copied!
Run script with conditional:
1
//check for exist variable
2
_HWIO.readyjs(function(){
3
cookie.set('a',1);
4
}, ['cookie']);
5
6
//run suddenly after this js (handle) has loaded
7
_HWIO.readyjs('js-cookie',function(){
8
console.log("~~ ready js-cookie")
9
});
10
11
//execute when user got interactive such as mouse move, click,scroll..
12
_HWIO.readyjs(null,function(){
13
_log('@when interactive');
14
});
Copied!
To know JS, CSS name (handle) you can right-click on your page > select "View page source" > find the JS or CSS URL you want to find the handle name. You can see id="example-xxx-js" or id="example-yyy-css" => the "example-xxx" and "example-yyy" will be JS handle name or CSS handle name of that JS/CSS file.
We will merge all JS and CSS to one file and load it lazy a bit. 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.
1
//combine php hook `hpp_delay_it_script`
2
_HWIO.add_event('run_script', function(v, js){
3
//when interactive
4
if( js.indexOf('ready js-cookie')!==-1)return 0;
5
return v;
6
});
7
</script>
8
<?php
9
});
Copied!
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 hpp_print_initjs hook - an example:
1
add_action('hpp_print_initjs', function(){
2
#if(is_home() || is_front_page())
3
if(isset($GLOBALS['hpp-criticalfile'])) {
4
?>
5
_HWIO.add_event('hpp_allow_js', function(v,att){
6
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;
7
});
8
<?php
9
}
10
});
Copied!
the event hpp_allow_js to allow / not allow, decide which JS file should be run or not.
Last modified 7mo ago
Copy link