防止部分html在手机中加载

问题描述:

我已经使用css和媒体查询,直到现在,以防止加载图像。现在我必须要求防止部分html,脚本在移动浏览器中加载。 这里是我用来阻止加载防止部分html在手机中加载

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

为HTML和JavaScript任何建议的图片?

您可以通过CDATAHTML comments防止浏览器中的HTML解析。但是您必须更改您的server side/template generated代码以防止加载任何HTML代码。

此外,您无法阻止从script标记src属性中加载脚本。您可以使用window.matchMedialazy-load/async加载脚本:

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*/) 
} 

或者使用requirejs

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

您也可以使用enquirejs

+0

伟大的方法。这个特性在requirejs中可用吗? –

+0

我编辑我的答案并添加链接到[enquirejs](http://css-tricks.com/enquire-js-media-query-callbacks-in-javascript/)。我认为enquirejs是你需要的。 – Pinal

看看这个: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

如果你想使用jQuery的JavaScript的: What is the best way to detect a mobile device in jQuery?

当然你会希望在移动设备检测后,如果要隐藏的元素添加display: none

+0

您好,希望阻止它们加载以节省带宽。不隐藏 –

下面是一些JavaScript代码,您可以运行该代码以包含仅限桌面的JS,并从移动浏览器中删除不需要的HTML元素。

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

}