简体   繁体   中英

Decide with Javascript which HTML Content to load

I determine via Javascript if the User is using a mobile or a Desktop Device. If he is using the Desktop Device, they should be shown the Desktop Versions of the Website, if he is using a mobile Device it should display the mobile Application. Now I'm just hiding the HTML part that is not needed with CSS but I want to get rid of this part due to loading times.

Now I want to know how I can decide by javascript which HTML Code should be loaded?

Thanks in Advance

I think media queries are the answer or you can use JavaScript of:

window.screen 

AvailableWidth = screenWidth;
AvailableHeight =screenHeight;
@media only screen and (max-width: 600px) {
< your css >
}

Refer to https://developer.mozilla.org/de/docs/Web/CSS/Media_Queries/Using_media_queries

I don't think you're too far off. I wouldn't have done it this way though and as others suggested I would have looked at making your HTML responsive. With that being said, you should (simply) reverse your logic. instead of a full page where you hide elements, you should start with a blank page where you inject HTML.

https://codepen.io/chancet1982/pen/VGxZyO

var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode("CLICK ME"); // Create a text node
btn.appendChild(t); // Append the text to <button>

function myFunction(x) {
    if (x.matches) { // If media query matches
      document.body.appendChild(btn);        
    } else {
        //Do something else..
    }
}

var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM