Prevent script from starting depending on device size

I have two ad scripts: one for the desktop and one for the mobile. Currently set display: noneto a specific size, etc. I am looking to prevent a script that is not currently showing due to work because scripts tend to be resource intensive and I am trying to speed up page load time. Is there a way to make scripts with only a certain width?

I thought:

if ($(window).width >= 768px) {
    <script> Do stuff </script>
} else {
    <script> Do stuff </script>
}

However, I had no luck with this (I'm not sure how the script works in the script). Is there another way to do this?

+4
source share
1 answer

, , . , script, .

var size,
    script;    

if($(window).width() > 768) {
    size = 'large';
} else {
    size = 'small';
}

script = $('<script />').attr('src', 'http://example.com/script-' + size + '.js');

$('head').append(script);
+4

Source: https://habr.com/ru/post/1618895/


All Articles