问题
Is this possible? I mean, I know you can use display: none; with media queries, but that does not prevent the nodes to be loaded, which is resource intensive. I don't want to hide them, I want to remove them.
That's why I used this:
function removeit() {
if ($(window).width() < 600) {
$('html').remove('aside');
}
}
And put it in the header, but I can't get it to work. What am I doing wrong?
PS: I tried using it with document ready function, but still not working on my iPhone. I keep seeing the aside sidebar.
PS 2: jQuery is loaded in the header, I have tried to put this snippet beneath the jQuery call.
回答1:
jQuery executes after the DOM is loaded. So the sidebar is loaded either way.
With CSS, you tell the browser to ignore styling the element but with jQuery you tell the browser to interact and manipulate the element, so my guess is you would actually get worse performance this way.
回答2:
This should work:
function removeit() {
if ($(window).width() < 600) {
$('body aside').remove();
}
}
To fire this automatically :
function removeit() {
if ($(window).width() < 600) {
$('body aside').remove();
}
}
$(function() {
removeit();
});
You could also add an window resize event and fire the removeIt in there (when user resizes the window or tablet/phone changes the perspective).
回答3:
you need to call a window.resize as metioned
try-
$(document).ready(function(){
$( window ).resize(function() {
if ($(window).width() < 600) {
$('aside').remove();
}
});
});
回答4:
Like provided answers are suggesting, chances are that you won't get any luck with jQuery for that.
A different approach could be to make the server side detect whenever a visitor arrives on your webpage using a mobile device. That way, you could send a different version of the page depending on what your visitors are using, hence loading only the necessary DOM elements.
What you could use with PHP:
php-mobile-detect (class)
回答5:
try this
before you must place blow in head tag
<meta name="viewport" content="width=device-width, height=device-height" />
and js
$(document).ready(function() {
if ($(window).width() < 600) {
$('html').find('.aside').remove(); //use class or tag name or id
}
})
or
$(document).ready(function() {
if ($(window).width() < 600) {
$('html .aside').remove(); //use class or tag name or id
}
})
回答6:
Your syntax is incorrect. Read the documentation:
jQuery Remove DOC
.remove() can be called on the jQuery object that references the node to be removed and the additional option is to pass a selector to the remove method. What you're saying is remove the HTML node that has the aside selector. The code isn't doing anything because aside is not a qualifying class or ID.
$('aside').remove(optional selector); would work, using the optional selector only if the aside is given one. Not necessary unless you have multiple asides, but filtering by unique ID would be a best practice.
来源:https://stackoverflow.com/questions/21549451/remove-html-from-dom-if-mobile-browser-with-jquery