Load JS Assets based on screen resolution

Hi.

How can I execute a js script depending on the screen size?

It would be something like this:

{% block javascripts %}
<script>
var width = {# sample code #}
   {% if screen < 980 %}
      {# javascript code #}
   {% endif %}
</script>
{% endblock %}

I’ve tested with

var w = window.innerWidth
if w < 980 {
   {# code #}
}

but no resuts.

I don’t know if this can be done directly in the Twig templates. Anyone who can help?

try:

if ((window.innerWidth || document.documentElement.clientWidth) < 980){ do some stuff }

Hi @lisekbox.

With your solution not work:

{% block javascripts %}
<script>
if ((window.innerWidth || document.documentElement.clientWidth) < 980) { 
  /* Script  */
  }
</script>
{% endblock %}

Viewing the html source the script code is still loading in devices upper 980px.

Hmmmm just made simple test…

<script>
  if ((window.innerWidth || document.documentElement.clientWidth) < 980) {
   console.log('test') 
  }
</script> 

and script is executing only on devices below 980px… but of course whole script code inside will be still loading on upper resolutions on page load, but will not execute instructions… If U dont want to load your script > 980 save code U want to run in file, then using JS create element script in footer with link to your file

Hi @lisekbox.

Indeed the JavaScript code appears in the source code of the page, but with your instruction it is not executed. I have done some tests and it works fine.

Thanks for everything.