Peleke
Peleke

Reputation: 961

Load javascript only for min-width

I want to load a specific javascript only when min-width is > 1000 px. Therefore I wanted to use this code which was mentioned here:

window.addEventListener('resize', function(){
    if(window.innerWidth > 568){
        ...execute script
    }
});

Somehow this doesn't work. Here is my full code block:

         var t = (0, s.qs)(".js-twitter-feed");
         window.addEventListener('resize', function(){
             if(window.innerWidth > 1000){
         if ("undefined" != typeof twitterFeed && t) {
             t.classList.remove("u-hide");
             var r = document.createElement("div");
             r.innerHTML = '<a class="twitter-timeline" data-height="500" href="https://twitter.com/'.concat(twitterFeed, '">Tweets by ').concat(twitterFeed, "</a>"), t.appendChild(r), (0, o.loadScript)("https://platform.twitter.com/widgets.js")
         }
             }
         });

What did I do wrong?

Upvotes: 0

Views: 332

Answers (1)

Andre Nuechter
Andre Nuechter

Reputation: 2255

A more performant way would be to use the window.matchMedia method to get a MediaQueryList and attach an eventListener to that.

Here's an example of how you can do that (the callback will be executed when the condition is met on page-load or when you resize the screen from below 300px to 300px or above):

window.addEventListener('DOMContentLoaded', () => {
  const callBack = () => console.log('do stuff');
  const mediaQuery = window.matchMedia('(min-width: 300px)');
  
  if (mediaQuery.matches) callBack();
  
  mediaQuery.addEventListener('change', (event) => {
      if (event.matches) callBack();
  });
});

Upvotes: 1

Related Questions