How to load or not a JS script (into the head section) based on screen resolution?

Tormy Van Cool picture Tormy Van Cool · Aug 6, 2015 · Viewed 7.7k times · Source

on a website, I have these lines on the tag

  <script type="text/javascript" src="http://www.domain.com/js/jquery.min.js"></script>
  <script type="text/javascript" src="http://www.domain.com/js/jquery.colorbox.min.js"></script>
  <script type="text/javascript" src="http://www.domain.com/js/inner-code-colorbox.min.js"></script>

Which are loading JS code, that shouldn't be loaded at all on portable systems

Is there a way to do it?

I tried in this way:

  <script type="text/javascript" media="only screen and (min-width: 950px)" src="http://www.domain.com/js/jquery.min.js"></script>

But it's not working

Thank you in advance

Answer

Maximillian Laumeister picture Maximillian Laumeister · Aug 6, 2015

Replace your script tags with this script tag, which will create the other three script tags ONLY of the window width is larger than a certain amount.

This answer does not rely on jQuery, so you can use it to determine whether you want to load jQuery.

<script>
    if (window.innerWidth > 500) {
        var head = document.getElementsByTagName('head')[0];

        var s1 = document.createElement("script");
        s1.type = "text/javascript";
        s1.src = "http://www.domain.com/js/jquery.min.js";
        head.appendChild(s1);

        var s2 = document.createElement("script");
        s2.type = "text/javascript";
        s2.src = "http://www.domain.com/js/jquery.colorbox.min.js";
        head.appendChild(s2);

        var s3 = document.createElement("script");
        s3.type = "text/javascript";
        s3.src = "http://www.domain.com/js/inner-code-colorbox.min.js";
        head.appendChild(s3);
    }
</script>