0

I have a bit of JavaScript/JQuery code that I have been tweaking in order to have a webpage switch CSS scripts if the page is resized too small, or if it starts up too small.

The resize seems to work great, but I think i may be cheating on the window.onload statement to make the resize check happen. I can see it when I start to load the page and see it have to "think" before switching to the narrow.css.

I am looking for suggestions on how to make this bit of code preform better, or be less taxing on a mobile connection.

"use strict";

var windowsize = $(window).width();

$(window).resize(function() {
  windowsize = $(window).width();

  if (windowsize < 600) {
    document.getElementById("myCSS").setAttribute("href", "css/narrow.css");
  } else {
    document.getElementById("myCSS").setAttribute("href", "css/mystyles.css");
  }
});

//force window size check at load to kick in if statement
window.onload = $(window).resize();

2
  • 3
    You should use media queries instead Commented Jul 28, 2015 at 4:32
  • 1
    Your approach isn't bad, if you were targeting browsers that didn't support media queries, but as you can see is every browser except IE8 caniuse.com/#feat=css-mediaqueries does. Commented Jul 28, 2015 at 4:36

2 Answers 2

4

css media queries are designed for this purpose: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries

To apply this approach with the details in your example you might do something like this:

@media (max-width: 600px) {
  /*CSS from css/narrow.css*/
}
@media (min-width: 601px) {
  /*CSS from css/mystyles.css*/
}
Sign up to request clarification or add additional context in comments.

1 Comment

I have marked myself a ToDo to switch this over to a CSS3 solution once I am done with my JavaScript training. Until then, I have removed the onload as suggested. Thanks everyone!
0
  1. It is probably best to have #myCSS set originally to the mobile stylesheet, and if the screen is too big, switch to the desktop stylesheet.
  2. No need to wait for the load event to execute; if the JS snippet is after #myCSS, then #myCSS is already in the DOM, and one can just write $(window).resize(); without window.onload =. This should prevent the browser from waiting till everything else is loaded before loading the stylesheet.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.