Today there's an open source JavaScript library that does this job: it's called Offline.js
.
Automatically display online/offline indication to your users.
https://github.com/HubSpot/offline
Be sure to check the full README. It contains events that you can hook into.
Here's a test page. It's beautiful/has a nice feedback UI by the way! :)
Offline.js Simulate UI is an Offline.js plug-in that allows you to test how your pages respond to different connectivity states without having to use brute-force methods to disable your actual connectivity.