Trying to follow Google Page Insights suggestions, I've got the "JS render block" recommendation for and it is related to jQuery
main file.
My site use WordPress with some plugins. One of the plugins throw its JS inline. So when I move jQuery
to load in the footer, or when I use "defer" mode to load it, I get jQuery is not defined
once the inline code fired.
I was trying to find a global solution to 'catch' all inline scripts and delay it after jQuery
main file is executed at the end of the document.
I wrote a solution that works great for me. It is very straight forward solution for my specific situation, but I failed to make this as a filter for the_content
or widget output. I would like to make this a global solution, so I wouldn't need to worry about any JS firing somewhere.
Any ideas how to make it work? Here my code so far, for this specific case, which runs through a shortcode:
/* Get shortcode HTML */
$widget_shortcode = do_shortcode($shortcode);
/* Take out all scripts into an array */
$delayed_scripts = array();
preg_match_all('#<script(.*?)</script>#is', $widget_shortcode, $match);
foreach ($match as $val){
$delayed_script = '<script '.$val[0].'</script>';
array_push($delayed_scripts, $delayed_script);
}
/* Remove all scripts from HTML */
$widget_shortcode = preg_replace('#<script(.*?)</script>#is', '', $widget_shortcode);
/* Echo filtered HTML */
echo $widget_shortcode;
And just before the closing </body>
tag:
foreach ($delayed_scripts as $script) {
echo $delayed_script;
}