Detect device and swap the CSS file - jQuery

后端 未结 1 554
我寻月下人不归
我寻月下人不归 2020-12-31 15:16

My web application target to major Smartphones and I need to change the CSS file according to device (if there are issues in the UI need to hit them), and I’m planning swap

1条回答
  •  醉梦人生
    2020-12-31 15:28

    1.Is it best practice?

    Depends on what you think of as best practice, also what best practice is in the context of your application and your company. One thing this makes me think about is: Can you guarantee all your pages will be using jQuery? If so then I think this is a good approach to achieve what you are after. An alternative would be to do this server-side, that would guarantee best-performance but there may be other reasons why you dont want to do this (maybe you dont have access to server-side code, or you want to maintain most of the functionality in the hands of front-end programmers).

    2.Is it good in performance?

    The short answer is no. On top of needing the 100K+ payload of jQuery to inject the CSS on the page. The way you've approached the problem at the moment is to wait for the whole page (and all dependencies) to load before adding styles to it. This will create a noticeable 'jump' between when the page gets displayed at first (without styles) and when the styles get loaded and everything moves around.

    Loading the CSS server-side will get rid of this, but I think you can still do this in the UI and keep the majority of your code-base in JavaScript which will make it easier to maintain. In order to do this, remove the bit where you wait for the document to be loaded before calling up your CSS file:

    
    
    
    
    

    To further improve performance you could use a solution that does not depend on jQuery, instead of

    $(".cssLink").attr("href", controlCss);
    

    you could add #cssLink to the stylesheet element and use the DOM to do the same:

    document.getElementById("cssLink").setAttribute("href", controlCss);
    

    This would make you code look as follows:

    
    
    
    
    

    This way you will remove the dependency on the 100K plus payload of jQuery before you can apply your stylesheets to the page.

    UPDATE:

    It is also possible to apply CSS rules based on screen size rather than device.

    Have you had a look at @media queries?

    0 讨论(0)
提交回复
热议问题