Prevent images from being downloaded to page on mobile site - html

How can I make it so that within the mobile version of my site the images are not downloaded to from the web server as these are large files that are not needed and not being used and therefore severely impacting the use of the mobile version of the site. Having looking at previous threads of such nature I saw that hiding the parent of the image using code such as below can benefit.
.parent {display:block;}
.background {background-image:url(myimage.png);}
#media only screen and (max-width:480px) {
.parent {display:none;}
}
The problem being I don't want to use background image CSS for SEO issues associated with them as I like to use Schema tagging etc ..so how can I prevent an IMG tag from being downloaded, as display:none; only hides the image rather than stopping it being downloaded.
Note: This is not for copyright protection issues e.g. preventing right click etc etc but for speed and ultimately size of the downloaded content to mobile.

This solution uses CSS to prevent background-images from loading and jQuery to prevent images from loading. I'm not familiar with any CSS solution that will prevent images from loading.
JS Fiddle: http://jsfiddle.net/CoryDanielson/rLKuE/6/
If you know the images height and width (or even ratio) ahead of time you could set the background-image for a bunch of fixed size DIVs. This might be applicable for icons and layout-type images. Look at the HTML/CSS below for an example of that.
Background Images
/* hidden by default */
aside {
display: none;
}
/* Pictures load for 'big screen' users.. pcs/tablets? */
#media screen and (min-width: 750px) {
aside {
display: block;
}
.catpicDiv {
height: 100px;
width: 100px;
display: inline-block;
border: 1px solid red;
background-image: url('http://img2.timeinc.net/health/images/slides/poodle-1-400x400.jpg');
background-size: cover;
}
}
and HTML
<aside>
<div class="catpicDiv"></div>
<div class="catpicDiv"></div>
<div class="catpicDiv"></div>
</aside>
Image Elements are a different story...
I don't know of any purely CSS solution to prevent them from loading the images. So I'd solve it like this:
Define IMG tags as follows
<img src="" data-src="url-to-image.jpg" />
Then, somewhere in the head of the document you need similar javascript
1) Function to load all of the images
function loadAllTheImages() {
$("img").each(function(){
$(this).attr('src', $(this).attr('data-src'));
});
}
2) Code to determine if the user is on mobile or a PC (slow vs fast connection) and then load the images.
This code isn't bulletproof, there are much more accurate and reasonable tests than this.
$(window).load(function(){
if ( $(window).width() > 750 ) {
loadAllTheImages(); // !
} else {
$("body").append("<a id='mobileCheck' href='javascript: void(0);'>I GOTS 4G, LEMME HAVE EM!</a>");
}
});
3) As well as maybe some code to activate a button to load the images anyways? Why not, I guess... ?
$(document).ready(function(){
$('body').prepend("<h1>" + $(window).width().toString() + "</h1>");
$('body').on('click', '#mobileCheck', function(){
loadAllTheImages(); // !
$("#mobileCheck").remove();
});
});
Similar solution as here and what I hypothesized in the comments:
Delay image loading with jQuery

There is no native solution in CSS that would prevent images from loading even if you hide them or set display to none.
You have to use some JS to achieve that result. If you are familiar with JS that should not be an issue at all. There are several plugins ready to go to do what you want. You can also write your own JS because its not that difficult.
Here is my code that loads images based on the screen size:
DEMO AT CODE PEN
It works without any libraries like JQ but if you use one of those it will automatically switch to it (Tweak it to your specific needs).
JS
// use jQuery or pure JS
if (typeof jQuery !== 'undefined') {
// jQuery way
// alert("jquery");
$(function() {
$(window).on('load resize', function() {
var products = $("[data-product-image]");
products.each(function(key, value) {
var bg = null;
if (window.outerWidth < 500) return;
if (window.outerWidth < 1000) bg = $(value).data("product-image-s");
if (window.outerWidth >= 1000) bg = $(value).data("product-image");
console.log($(window).outerWidth);
$(value).css({
'background-image': 'url(' + bg + ')',
'background-position': 'center',
'background-size': 'cover',
});
});
});
});
} else {
// Pure JS way
// alert("JS");
(function() {
window.addEventListener('load', wlImageLoader);
window.addEventListener('resize', wlImageLoader);
function wlImageLoader() {
console.log('event! Trig trig');
var all = document.getElementsByTagName("div");
var products = [];
for (i = 0; i < all.length; i++) {
if (all[i].hasAttribute('data-product-image')) {
products.push(all[i]);
}
}
Array.prototype.forEach.call(products, function(value) {
var bg = null;
var curent = window.getComputedStyle(value).getPropertyValue('background-image');
console.log(curent);
if (window.outerWidth < 500 || curent != 'none') return;
if (window.outerWidth < 1000 && curent == 'none') bg = value.getAttribute('data-product-image-s');
if (window.outerWidth >= 1000 && curent == 'none') bg = value.getAttribute('data-product-image');
// if (window.outerWidth >= 2000 && curent == null) bg = value.getAttribute('data-product-image-l');
if(bg == null || curent != 'none') return;
value.style.backgroundImage = "url(" + bg + ")";
value.style.backgroundPosition = "center";
value.style.backgroundSize = "cover";
curent = window.getComputedStyle(value).getPropertyValue('background-image');
console.log(curent);
});
}
})();
}
HTML
<div data-product-image="img/something_normal.jpg" data-product-image-s="img/something_small.jpg" id="p3" class="product">
However if you are a time loading freak you probably prefer to write your code natively in JS as you often don't use most of the jQuery library. For fast internet connection this is not a problem but if you target mobile devices on country side that might make a difference.

I would suggest combining perhaps the #import and #media commands to only #import the stylesheet which contains images if the #media tag meets you criteria (say, over a certain resolution).
So by default you wouldn't import the stylesheet which applies the BG image, you'd only end up doing it if you had determined the site was 'non-mobile'..if that makes sense!
The W3c site has some decent examples of combining the rules:
http://www.w3.org/TR/css3-mediaqueries/#media0

Related

Prevent static files inside a CSS from being displayed before the page is loaded

I am modifying some JSP files, and every time I upload a new version, if people don't update the cache, the styles are not rendered as they should be; it is looking not good and without styles applied.
To solve this problem, I have followed an example from Stack Overflow that adds a numeric value to the CSS file, preventing it from being cached in the browser. The specific link I've seen is this one:
https://wpreset.com/force-reload-cached-css/
But I've found that whenever I press F5 or navigate to other JSP's that apply the same stylesheet, the files that are part of that CSS file are always seen just before rendering. I added a GIF with a dummy example to exhibit what I mean:
Animated GIF demonstrating the problem
How could I avoid this?
Would something like the following help?
/* CSS */
.no-js #loader { display: none; }
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
|
// Js
$(window).load(function() { // Wait for window load
// Animate loader off screen
$("#loader").animate({
top: -200
}, 1500);
});
Like it is used here.
I have already been able to solve it.
In the end I have chosen to nest inside a window.onload, the document.ready like this:
window.onload = function () {
document.getElementsByTagName("html")[0].style.visibility = "visible";
var h, a, f;
a = document.getElementsByTagName('link');
for (h = 0; h < a.length; h++) {
f = a[h];
if (f.rel.toLowerCase().match(/stylesheet/) && f.href && f.href.indexOf("custom-common.css") != -1) {
var g = f.href.replace(/(&|\?)rnd=\d+/, '');
f.href = g + (g.match(/\?/) ? '&' : '?');
f.href += 'rnd=' + (new Date().valueOf());
}
}
$(document).ready(function () {
$('.main-link').click(function () {
And change the visibility of the html document. I have omitted the rest of the code, but you can get an idea. Many thanks to Robert Bradley and Adam for shedding light and helping me.

Can't measure Clientwidth of Html-Image in Firefox

I am trying to place markers on points of interest (poi) on an Image.
These poi have been set in a different software and were stored in a database. The position is determined by their pixel position relative to the original Image. In my webapp the Images are scaled down thanks to panzoom.js (a plugin irrelevant to my question I think). I got the right formula to scale the markerposition, the only Problem is:
In firefox I'm unable to read the Images size in time (In Chrome that's not an Issue).
This is the Code
$(document).ready(function ()
{
var imagectrl = document.getElementById('<%= img.ClientID %>');
var hiddenfield = document.getElementById('<%= hf.ClientID %>');
if (hiddenfield.value == "")
{
var myWidth;
var myHeight;
myWidth = imagectrl.clientWidth;
myHeight = imagectrl.clientHeight;
hiddenfield.value = myWidth + ';' + myHeight;
__doPostBack();
}
});
If I do a postback manually (clicking a button that shows the Image in higher quality) the size gets written correctly.
I've also tried calling an identical function from Code behind when my X or Y are 0, but nothing worked.
What can i do to get the Images size when first loading the page?
Firefox has a different implementation on asynchronous operations like image loading than Chrome. I guess this could be the reason why in Chrome you can access the image right away with $(document).ready, but in Firefox the image source gets loaded after the document is ready - thus clientWidth and clientHeight will be undefined.
Solution: Define an onload event handler on your image and put your logic into that method:
$(document).ready(function ()
{
var imagectrl = document.getElementById('<%= img.ClientID %>');
var hiddenfield = document.getElementById('<%= hf.ClientID %>');
imagectrl.onload = function() {
if (hiddenfield.value == "")
{
var myWidth;
var myHeight;
myWidth = imagectrl.clientWidth;
myHeight = imagectrl.clientHeight;
hiddenfield.value = myWidth + ';' + myHeight;
__doPostBack();
}
}
});
I found a Solution:
No matter what I did, the Image itself can't be measured in time.
So i gave the Image the height of it's surrounding control via CSS and used
AddHandler dvGalerieFill.Load, AddressOf Me.measure_height
in the Page_Load method to react to the loading of the surrounding control.
In "measure_height" I called my Javascript function.
Through the height of the control (wich is the height of my image)
I can calculate the width of my image as height and width rescale with the same factor.

Is it possible to hide an html element if dynamic content requires more space?

I would like to hide an html Element (in my case a headline) only when the dynamic content of the site expands so far vertically that a scrollbar would appear. I am aware how to hide an element but I don't know how to trigger the event. I am searching for something like the #media rule in css, only that it shouldn't be triggered on the viewport resolution, but the size of the content (vertically).
Does anyone know a solution to this?
Thanks in advance!
Thanks to Nicks comment I figured out a solution.
If anyone is looking for the same thing, here is a working Javascript solution (no JQuery needed):
var callback = function(){
// Handler when the DOM is fully loaded
// Check if the body height is bigger than the clients viewport
if (document.body.scrollHeight > document.body.clientHeight) {
// Assign a class with display:none (in my case 'hide')
document.getElementById("headline").className = 'hide';
}
};
// This part ensures that the script will be loaded once the site is loaded
if (
document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)
) {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
With help by https://www.sitepoint.com/jquery-document-ready-plain-javascript/

Change background dependent upon arriving URL

Hi and hope someone can help.
I have a live site and also a development site where I test out new code before deployment but basically they have the same content e.g.
Live = www.myserver.com/live/index.html
Development = www.myserver.com/development/index.html
Is there a way of setting the (say) CSS background property dependent upon the url that has been used to arrive at the site.
My current CSS =
body {
background: #eff;
/* change this to background: #ccc; if on development site */
margin:25px;
}
Why?
Well, I frequently find myself uploading or testing new code on the wrong site.
Not a big issue I know but useful if I could have a visual clue as to which site I'm testing.
My thanks for your interest.
Now Solved Thanks for input from #Adam Buchanan Smith, #Dekel and Mr Green.
I sort of used #Dekel's logic but changed it to jQuery along the following lines:
<script>
$(document).ready(function(){
// Set background dependent upon url i.e. www.myserver.com/cab or www.myserver.com/cab2
// cab2 is the development site, cab the live site
// Also change text in div id="live" from 'Live Site' to 'Development Site' if arrives at by cab2
if (document.location.pathname.indexOf('cab2') > -1){
$('body').css({"background":"#BFFFDF"});
document.getElementById('live').innerHTML = "Development Site";
} else {
$('body').css({"background":"#efffff"});
document.getElementById('live').innerHTML = "Live Site";
}
}
</script>
My thanks to all for your interest!
Not something you can do in pure html/css, but you can use both javascript and server side language for that.
In javascript you can check if the document.location.hostname or document.location.pathname to check the domain/url you are currently using.
In javascript for example you can use:
if (document.location.pathname.indexOf('development') > -1) {
body = document.getElementsByTagName('body')[0]
body.setAttribute('class', body.getAttribute('class') + ' development')
}
Using PHP you can use $_SERVER['REMOTE_HOST'] and $_SERVER['REQUEST_URI'].
if (strpos($_SERVER['REQUEST_URI'], 'development')) {
echo "<body class=\"development\">";
} else {
echo "<body>";
}
And in the css file you can use:
body {
background: #eff;
}
body.development {
background: #ccc;
}
Theoretically something like this could work for you in just plain javascript using document.referrer;
<body onload="checkURL()">
</body>
<script>
function checkURL(){
var testPage = "www.testpage.com";
var livePage = "www.livepage.com";
var lastPage = document.referrer;
if (lastPage == livePage){
//do something here
}
else if {lastPage == testPage}
//do something else
}
else{
//umm what did you do?
}
</script>

Control scrolling on webkit browsers

I have a one page website and I need effect like this website. When user scrolls down, it should scroll right to the next page. You can test that effect by opening the second link in chrome and try scrolling up and down. I know there is nothing much but I have tried researching about everything possible and I just cant figure out a way top even start this functionality. I don't need to be spoon fed so just point me into the right direction by providing me a start and I will try and do the rest. Thanks.
Here's my advice: first of all, you need to understand the core functionality. Try debugging the website and searching for the effect's responsible files.
For your start, you should study about HTML5, CSS3 and Accordions. The HTML5 will help you improve the scrolling functions. CSS3 is resposible for the effect. And "accordion" is the name of the effect that scrolls straight to the page from the link you clicked on the menu.
The problem is that working with HTML5, you will find a few cross-browser issues ahead. An easy fix is to use the html5shive.js, that "forces" IE to understand HTML5 tags.
An alternative for this, is using jQuery, that will give you the same effect without trouble. You should look for "jQuery navigation with smooth scroll".
You can also use only accordion, which is way more easy.
There's a left sidebar that allows you to click on the links and leads you to the page with the scrolling effect. That's an accordion, combined with jQuery. If you don't pretend to include a menu with links, you can only use jQuery for the scroll.
Here's a good start for you: jsfiddle.net/7ZVb7/1383/
:)
This is how it is done:
function scrollingBaby(e) {
var t = Math.floor(e.pageY / $(window).height());
e.wheelDeltaY < 0 ? t++ : e.wheelDeltaY > 0 && t--;
var n = $(".winHeight").size();
n--;
t < 0 ? t = 0 : t > n && (t = n);
//alert(t);
console.log($('.moveThis'+t).offset().top);
$("html,body").animate({
//scrollTop: $(window).height() * t
scrollTop: $('.moveThis'+t).offset().top
}, 400, "easeInOutExpo", function () {
setTimeout(function () {
onAnimation = !1
}, 1200)
})
}
var slideActual = 0,
flag = 0,
reveal = 1,
revealPro = 0,
offset = 0,
heightInfo = 0,
widthInfo = 0,
onAnimation = !1;
(function (e) {
var t = navigator.platform.toUpperCase().indexOf("WIN") !== -1;
window.onmousewheel = document.onmousewheel = function (e) {
e = e || window.event;
e.preventDefault && e.preventDefault();
if (onAnimation == 0) {
onAnimation = !0;
scrollingBaby(e)
}
e.returnValue = !1
};
t && IE8JETEMMERDE();
sliderSize();
setTimeout(function () {
checkImageSize()
}, 800);
countMedia(1)
})(jQuery);
Where in, ".winHeight" is the class that is on all the 'pages' or divs that would need to be animated in this way and '.moveThis0', '.moveThis1' etc are the classes that are applied so that we can gather the offset of divs and direct them to top of the page.