kp_marz
kp_marz

Reputation: 21

Load External JavaScript on Desktop Only

I have went through a ton of answers, and I can not get anything to work for me. Please be patient and specific as I am a newbie when it comes to using JavaScript.

I am attempting to get an external JavaScript file to load on Desktop only. Below is the code I am currently using, but it is not working. Can someone please help me achieve this.

<script>
(function() {
if( window.innerWidth > 600 ) {
    var theScript = document.createElement('script');
        theScript.type = 'text/javascript';
        theScript.src = 'www.siteminds.net/m/1.6/mind_loader.php?pid=y2w6z8B3N31&cast_id=v1532315&autoplay=1&avname=jackie&wc=1&avnum=15&band_type=av';

    var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(theScript, s);
}
})();
</script>

I am placing this code in the head section, however, the script is not running.

The website is responsive using respond.js. I also added enquire.js in an attempt to use that method (which I also couldn't get to work)

Upvotes: 1

Views: 3584

Answers (2)

kp_marz
kp_marz

Reputation: 21

This is what ended up working for me.

<script>
var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

if ( width > 600) {
document.write('<script src="//www.siteminds.net/m/1.6/mind_loader.php?pid=y2w6z8B3N31&cast_id=v1532315&autoplay=1&avname=jackie&wc=1&avnum=15&band_type=av" async><\/script>');
}
</script>

Upvotes: 1

jfriend00
jfriend00

Reputation: 707318

Probably, the main issue is that you must include the protocol on the URL so:

'www.siteminds.net/m/1.6/mind_loader.php?pid=y2w6z8B3N31&cast_id=v1532315&autoplay=1&avname=jackie&wc=1&avnum=15&band_type=av'

needs to be:

'http://www.siteminds.net/m/1.6/mind_loader.php?pid=y2w6z8B3N31&cast_id=v1532315&autoplay=1&avname=jackie&wc=1&avnum=15&band_type=av'

Your code could also fail if there were not already some script tags. This version is not vulnerable to that:

<script>
(function() {
if( window.innerWidth > 600 ) {
    var theScript = document.createElement('script');
    theScript.type = 'text/javascript';
    theScript.src = 'http://www.siteminds.net/m/1.6/mind_loader.php?pid=y2w6z8B3N31&cast_id=v1532315&autoplay=1&avname=jackie&wc=1&avnum=15&band_type=av';

    var head = document.getElementsByTagName('head')[0];
    head.appendChild(theScript);
}
})();
</script>

Note: a test for innerWidth > 600 is not even close to a fail-proof way to detect a desktop installation as even a tablet in landscape mode will pass that test.

Upvotes: 4

Related Questions