Open.js file when Mediaquery is larger than 1024px

Asked

Viewed 50 times

1

At the end of index.php (responsive layout) you have a call to

< script type='text/javascript' src='desk.js'>< /script>

It turns out that this JS will only act with Mediaquery larger than 1024px.

I ask you: It is possible to make an IF condition in Java or in the CSS itself that opens this JS ?

JS is heavy and mobile has no function.

1 answer

1

You can take the screen size by window.screen.width or window.innerWidth and if it is smaller you can add the js file. ex:

function desktop(){
       if(window.screen.width >= 1024){
           var sc = document.createElement('script')
           sc.src = "desk.js"
           document.querySelector('body').append(sc)
       }
 }

Reference

  • Thanks Rodolfo for the guidance. But it didn’t work. I put your code with < script>, then with < script type="text/javascript">, at head and end < /body>. It seems that JS is not read. (use this JS for more than 10 years, open img.peq frame for img.gde - Note: works normal) Did I miss a command that I didn’t notice? Thank you for your cooperation

  • if it only copied and pasted it does not work because it is a function and needs to be called, put it this way (Function desktop(){ if(window.screen.width >= 1024){ var sc = Document.createelement('script') sc.src = ".js desk" Document.querySelector('body').append(sc) } })() will work by including it

  • Rodolfo. Didn’t work: This one worked: But it’s huge (much bigger than my file) It’s illogical to use an external one to open a smaller internal one. < script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script>if ( $(window).width() >=1024) ' Document.write(unescape("%3Cscript src='desk.js' type='text/javascript'%3E%3C/script%3E"); }</script> Note: I read that using Document.write in js is outdated. And my desk.js has. Is this the cause of not accepting your call? Thank you for your attention

  • I ended up doing the test here, usually I don’t use it ; in my code and as this inline it needs to use, the correct one is (Function desktop(){ if(window.screen.width >= 1024){ var sc = Document.createelement('script'); sc.src = "desk.js"; Document.querySelector('body').append(sc)} })() using the ;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.