Detecting a mobile browser (Device Sniffer) with javascript

I recently created a custom cursor for a website that looked like this:

What I wanted to make sure, was that this custom cursor did not appear on touch screen devices.

The solution:


//set a variable to check if the device has a touchscreen
var hasDeviceTouch = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);


//if the device does not have a touch screen, then run the code that controls the custom cursor
if (!hasDeviceTouch ) {
const cursor = document.querySelector('.cursor');
document.addEventListener('mousemove', e => {
cursor.setAttribute('style', 'top: '+(e.pageY - 6 )+'px; left: '+(e.pageX - 6)+'px;');
})
}

Finally, where I called the cursor div on the main page, I added this code so as to only output the source code to pages that did not have a touch screen:


if (!hasDeviceTouch ) { document.write("< div class='cursor'>"); }

Defer parsing of JavaScript in GTmetrix results

I have added a youtube video embed to the home page on my website, which works great, However, when I analyse this page using with https://gtmetrix.com one of the issues I am seeing is error asking me to defer the leading of youtube video, to essentially load this iframe after all of my assets are finished loading.

Here’s what my initial code looked like:

<iframe width="680" height="383" src="https://www.youtube.com/embed/c_QLUv9FUHo?showinfo=0&amp;autoplay=0&amp;rel=0" frameborder="0" gesture="media" allowfullscreen=""></iframe>

and here is the issue being highlighted by gtmetrix:

gtmetrix defe youtube

I made a couple of changes to this code, namely adding an ID of “youtube”, and removing the src attribute, but adding a data-src attribute with the same value. Here’s my amended iframe code:

<iframeid="youtube" src="" data-src="https://www.youtube.com/embed/scDpX9nIUVU?showinfo=0&amp;autoplay=1&amp;rel=0"frameborder="0"gesture="media"allowfullscreen=""></iframe>

I then added a fewof lines of javascript at the bottom of my page.

functionvidDefer() {
varyoutubeDefer = document.getElementById('youtube');

youtubeDefer.setAttribute('src',youtubeDefer.getAttribute('data-src'));
}
window.onload = init;

I ran the gtmetrix test once more, and here is the result so it went from an F rating, to a B rating.

Please leave your comments below if this helped you.

Cheers,
Jamie