Maclean Pinto
Maclean Pinto

Reputation: 1135

Prevent parts of html from loading in mobile

I have used css and media queries till now to prevent images from loading. Now i have to requirement to prevent parts of html, scripts from loading in mobile browsers. Here is how i used to prevent images from loading

@media (min-width:601px) {
   .image {
      background-image: url(http://www.example.com/wp-content/uploads/2013/05/img.jpg);
      width:700px;
      height:350px;
   }
}

Any suggestions for HTML and JavaScript ?

Upvotes: 0

Views: 1061

Answers (3)

Alex
Alex

Reputation: 11245

You just can prevent HTML parsing in browser by CDATA or HTML comments. But you must change your server side/template generated code to prevent loading any HTML code.

Also you can't prevent loading script from script tag src attribute. You can use window.matchMedia and lazy-load/async for loading script:

if (window.matchMedia('min-width:601px')) {
   (function (callback) {
       var script = document.createElement('script');
       script.src ='url';
       script.onload = callback;
       document.documentElement.firstChild.append(script);
   })(callback/*if needed*/)
}

Or using requirejs:

if (window.matchMedia('min-width:601px')) {
   var someModule = require('moduleName_or_path');
}

Also you can use enquirejs.

Upvotes: 2

Chirag Bhatia - chirag64
Chirag Bhatia - chirag64

Reputation: 4516

Here's some JavaScript code that you can run to include desktop-only JS and remove unwanted HTML elements from mobile browsers.

if (window.innerWidth > 601) {
    //Run JS code that is to be loaded only on desktop browsers
    console.log("This will run only in desktop browsers");
}

if (window.innerWidth < 601) {
    //Remove HTML elements not to be shown in mobile devices
    document.getElementById("extra-info").remove();

}

Upvotes: 0

grim
grim

Reputation: 6769

Take a look at this: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

If you want to use javascript of jQuery: What is the best way to detect a mobile device in jQuery?

Of course add a display: none on the element you want to hide after detecting if on mobile device.

Upvotes: 0

Related Questions