I have an Rmd report which contains a large asset (in the form of a leaflet map htmlwidget) that I do not want to be loaded if the viewer is on mobile. Is there a way to do this? I am aware of using css media queries but that will prevent an item from being displayed, but it doesn't prevent it from being loaded which is what I'm going for here.
I have found some recommendations for a similar case using img and lazy loading, but I don't believe that is applicable here.
I can see a somewhat hacky way of achieving this using shiny::renderUI and jquery passing a message back to shiny with the window's width, but would prefer to do it entirely in rmarkdown or if there is a more elegant way.
Thanks
Edit:
I have included a reprex below that shows the issue I would like to solve
---
title: "no load on mobile reprex"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE)
library(htmltools)
library(leaflet)
library(spData)
# In practice, this would be a large map object of several MBs that we don't
# want the viewer to see *or even to load* if they are on mobile
mapdata = us_states
```
```{js}
// For simplicity, let's just use the case of a small window width
$( document ).ready(function() {
var window_width = $(window).width();
console.log('window_width is ',window_width);
});
```
```{css}
/*
This CSS will hide the map when the screen is small, but it has 2 issues.
1. it will dynamically reevaluate when the window size, whereas I would only like one check on page load
2. if you look at the network tab, the map still gets loaded, which is a waste of bandwidth for mobile users
*/
@media only screen and (max-width: 768px) {
#desktopOnlyContent {
display: none;
}
}
```
## A message to all users
```{r}
h3('This message is for all users')
```
## Different content for different users
```{r}
div(id = 'desktopOnlyContent',
h3('If you can see this, that means you have a large screen'),
p('If you dont have a large screen then this should not even be visible in the elements tab of the devtools inside your browser, because if it is, then it is wasting bandwidth'),
leaflet(elementId = 'desktopMap') |>
addPolygons(data = mapdata)
)
```
## Another message to all users
```{r}
h3('This message is also for all users')
```