JavaScript runs on the client side, interpreted by the visitor browser, so it can be an intelligent solution and sometimes may be the last resort for the web programmer and the server administrator.
From the server admin view, and in some situations when you use a hard cache system for your website pages, for example, when using the Cloudflare Cache Everything page rule feature, you will miss all server-side flags, checks, or controls you may count to take action.
So JavaScript is here to help, and yes will help from the client side.
We will take an example scenario of How to use JavaScript and use it, detect our web application and website user device type, iPhone, iPad, Android, etc… Then we take action to even inject extra CSS or JS files, or make a user redirection.
JavaScript Detect User Device And Take Action
In the header section of our web template, we can add the following JavaScript block of code to determine if the user comes to our website using one of the following devices (iPhone, iPad, or Android) using the JavaScript userAgent property.
<script language="javascript"> if (navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/Android/i) ) { Â Â // do some actions } </script>
JavaScript Inject CSS Or JS Files
Now we will inject an extra CSS file based on our above device detection
<script language="javascript"> if (navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/Android/i) ) { document.write('<link rel="stylesheet" type="text/css" href="/sites/all/themes/nets/css/mobile-commons.css">'); } if (navigator.userAgent.match(/Android/i)) { document.write('<link rel="stylesheet" type="text/css" href="/sites/all/themes/nets/css/fix-Android.css">'); } if(navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) { document.write('<link rel="stylesheet" type="text/css" href="/sites/all/themes/nets/css/fix-iphone-ipod.css">'); } </script>
JavaScript Redirection
We may need to make a redirection, for example, if we check out that the user’s device is an Android one, we will redirect the user to another webpage version.
<script language="javascript"> var targetURL= {"url":"https:\/\/netslovers.com\/category\/games\/","delay":"0"}; if (navigator.userAgent.match(/Android/i)) {
setTimeout(function () { window.location = targetURL.url; }, targetURL.delay);
} </script>
Now we can redirect based on our targetURL values, the URL, and Delay if we detect that the user device is Android.