Autoptimize: no more broken pages due to CSS/ JS not found!

When cached HTML links to deleted Autoptimized CSS/ JS the page is badly broken … no more with a new (experimental) option in AO27 to use fallback CSS/ JS which I just committed on the beta branch on GitHub.
For this purpose Autoptimize hooks into template_redirect and will redirect to fallback Autoptimized CSS/ JS if a request for autoptimized files 404’s.
For cases where 404’s are not handled by WordPress but by Apache, AO adds an ErrorDocument directive in the .htaccess-file redirecting to wp-content/autoptimize_404_handler.php. Users on NGINX or MS IIS or … might have to configure their webserver to redirect to wp-content/autoptimize_404_handler.php themselves though, but those are smart cookies anyway, no?
If you want to test, you can download Autoptimize 2.7 beta here and replace 2.6 with it.

Redirecting to AMP (reader mode) for mobile

I’m not a big fan of AMP but I do have it active here on this blog using the official AMP plugin for WordPress, using it in “Reader” (aka “classic”) mode. That’s as far as I want to take it, but suppose (as was the case for an Autoptimize/ Critical CSS user I was helping out) you want to redirect all mobile traffic to AMP, then you could use below code snippet to do just that.

add_action('init','amp_if_mobile');
function amp_if_mobile() {
  $_request = $_SERVER['REQUEST_URI'];
	if ( strpos( $_request, '?amp' ) === false && strpos( $_request, '&amp' ) === false && ! is_admin() && wp_is_mobile() ) {
    if ( strpos( $_request, '?' ) === false ) {
      $_amp = '?amp';
    } else {
      $_amp = '&amp';
    }
    $amp_url = home_url() . $_request . $_amp;
    wp_redirect( $amp_url );
    exit;
  }
}

It might be a little rough around the edges, but it (mostly) gets the job done 😉