0

Is it possible to not load an element in the DOM of an HTML page with CSS or Javascript ?

I have a <div> that I want to load only when the resolution is a smartphone one. Just to do a display: none; while I don't want it doesn't work because a script (iScroll) is linked to the <div>.

I really have to not load it in the DOM (or to delete it from the DOM when I load my page).

I believe that I can do it using removeChild(). But is there a way in CSS ?

Emilie
  • 668
  • 1
  • 9
  • 21

3 Answers3

2

I think you are missing some details but if you are trying to prevent a image from loading there is a dirt way of doing this. If you only use the image as a 'background-image' in the css and set the "display: none" the image will only load if you change the "display"

samuel.molinski
  • 1,119
  • 10
  • 24
  • Huh. you learn something new everyday. Even if this doesn't end up answering the question, good trick! – MaxPRafferty Nov 07 '12 at 16:51
  • Out of all ways in 2021 from attempting to use Javascript to .remove my images inline from the DOM to using display: none on images inline + extra type of methods I've came across ... This answer right here is finally the "right way" to not load resources! I replaced my inline GIFs to a DIV GIF Container with a BG Image and then set a media query for under tablet size to display: none; and background: none; ... Tested on Network and NO MORE GIFS loading! My waterfall is now clean and super quick. This saved me from loading 28mbs of GIFs on mobile using Webflow. Thank you 2012-Samuel. – DoPeT Jan 23 '21 at 19:28
1

No, if the content exists in the file/resource you're requesting you have to receive it and then (as you say) manipulate it out of the DOM. CSS can only alter its appearance.

A.M. D.
  • 928
  • 6
  • 10
  • This answer will help you: http://stackoverflow.com/questions/1804991/remove-dom-element-without-knowing-its-parent – A.M. D. Nov 07 '12 at 16:57
1

No. Css does not interact with the DOM, and your page must load before the DOM exists.

You can remove an element as follows:

var itemToRemove = document.getElementById("itemToRemove");
document.body.removeChild(itemToRemove);

If your element is nested deeper in the DOM, you'll need to Walk the DOM: http://javascript.about.com/od/byexample/a/dom-walknodes-example.htm

I suppose, theoretically, you could prevent an element from loading with some voodoo ajax, but i wouldn't recommend that.

Additionally, the JQuery remove() method is a popular alternative to the DOM method above, as it can be called on the element itself.

MaxPRafferty
  • 4,819
  • 4
  • 32
  • 39