0

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 ?

Maclean Pinto
  • 957
  • 2
  • 13
  • 35

3 Answers3

2

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.

Pinal
  • 10,391
  • 12
  • 45
  • 62
  • Great approach. Is this feature available in requirejs? – Maclean Pinto Jan 23 '14 at 09:00
  • I edit my answer and add link to [enquirejs](http://css-tricks.com/enquire-js-media-query-callbacks-in-javascript/). I think enquirejs is what you need. – Pinal Jan 23 '14 at 09:17
0

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.

Community
  • 1
  • 1
grim
  • 6,191
  • 11
  • 32
  • 52
0

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();

}
Chirag Bhatia - chirag64
  • 3,808
  • 2
  • 23
  • 31