4

I have two ad scripts, one for desktop and one for mobile. Currently, one is set to display: none on a certain size and so on. I'm looking to prevent the script that is currently not shown from running whatsoever, because the scripts tend to be resource intensive and I'm trying to speed up the page load time. Is there any way to only make scripts execute at a certain width?

I was thinking:

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

However I've had no luck with this (I'm not sure how a script within a script would work). Is there another way to go about this?

Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
Chris Waszczuk
  • 125
  • 2
  • 12
  • Why do you need the script tag? Just use if ($(window).width >= 768px) { Do stuff } else { Do stuff } – Jodi Supporter Dec 07 '15 at 13:39
  • It's an ad script from an external source, I guess i could pull the information from it, but i'd rather keep it as a script tag – Chris Waszczuk Dec 07 '15 at 13:43
  • then you might add the script tag dynamically: http://stackoverflow.com/questions/13121948/dynamically-add-script-tag-with-src-that-may-include-document-write – Peter Porfy Dec 07 '15 at 13:48

1 Answers1

4

Instead of making scripts execute at certain widths, consider splitting them up in different files and load those at certain widths. That way you only load the script you actually need.

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);
Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
  • A side note, i have this in place yet i'm getting a warning "Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.". Do you happen to know how i can go about solving this? – Chris Waszczuk Dec 08 '15 at 17:45
  • You should probably not use `document.write` then. Since you're using jquery anyway try appending text/html to the document by using `.html()` and `.text()` – Stephan Muller Dec 09 '15 at 10:54