Load content dynamically & resize event

Remember that PHP (wordpress) run on server, javascript run on browser.

So, what you intend is:

  1. load an url of your site (a GET request is sended to server)
  2. Server respond with a minimal html containing enquire.js and your script with enquire.register stuff
  3. enquire.js recognize resolution and run a js function
  4. the function triggered by enquire.js run an ajax call (this is a second request to server)
  5. Server respond to the ajax call with the html from your template and using jquery.html() you put the html in the body of page. If want avoid loading jquery you can output json from server and use a pure js templating engine e.g. Pure to convert json to html in the body.

Is this optimized? Not for me.

  • For every page load you run 2 server requests instead of one
  • On the first request you need some scripts (enquire.js, your enquire.register script, jquery or templating script) that do nothing in the page, only scope is loading the content
  • even if jquery or templating script are fast, static html outputted from server is always shown faster

In short, you do a lot of work to optimize site for mobile devices, with chances to get the opposite result.

This workflow can be useful for small parts of site, not for entire content. At least, not for me.

For me, in that case, I’d

  1. for every template file create 3 versions, e.g. page.php | page-tablet.php | page-phone.php or header.php | header-tablet.php | header-phone.php and so on
  2. On init, use a server detection method, like Mobile Detect to sniff the current device, put it in a static variable class or in a constant
  3. Add a hook for template_include filter that append "-{$device}" to every template required. (e.g. if is required ‘page.php’ it returns ‘page-tablet.php’ if current device is a tablet)
  4. Using the same $device global accessible variable, register js scripts related to the device
  5. In the template file use get_header($device) instead of get_header() just like get_footer($device), get_sidebar($device). Also use get_template_part('part', $device) instead of get_template_part('part') and so on.

In this way you have

  • one request per page and not 2
  • every device load its own content
  • html output is demanded to server and not to client, and this is better for performance

For little parts you can use the enquire.js method and flavor everything with some media queries. E.g. for tablets you can use the same template of desktops and use enquire.js + ajax to add some content if resolution is over a certain breakpoint.

Working with wordpress, in my opinion, this is the best way to get mobile optimized version of a site.