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:
//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(){returntypeof 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 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.
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: