I build a website and i want to ask the user when each time visit the site, if he want to display images or not. and if not, i want to do not load them and display the page without any img tag
i tried this, but this is not useful because the page will be loaded
function load_img () {
if (!confirm("Do you want to load the images on your site?")) {
var images = document.getElementsByTagName("img");
var l = images.length;
for (var i=0; i<l; i++) {
images[0].parentNode.removeChild(images[0]);
}
}
}
i need some code that don't load any img tag when the page load,
and not a code that hide or remove the images after the page is loaded and the images are displayed
can someone help me please with this javascript code
thank you
You can take a look at lazyload plugin for jQuery. What this plugin does is load the image when the image is on the visible area of the page.
Their idea is to put the original URL to the image in data-original attribute and in the src attribute put some small image e.g. 1x1 transparent gif like this:
<img data-original=“img/example.jpg” src=“img/grey.gif” />
and then you are able to load all the images whenever you want to just by replacing the the src.
this is a simple javascript code that you can try:
window.onload = function() {
if( confirm('Images?') ) {
var img = document.getElementsByTagName('img');
for(i in img) {
var original = img[i].getAttribute('data-original');
if( original.length ) {
img[i].setAttribute('src', original);
}
}
}
}
You could try jquery : $("img").remove();
It would be better to solve this problem from the server side!
Make start page with a link to a version of the page with images and one without the images. You can write a server side script (PHP?) to show or hide the images. Simple removing the images could break the page design. Also removing html image tags does not do the trick. What about background images, some in css files, ...
If you like to do this an on the client side with javascript you have to remove all images and add them manually with javascript.
Using jQuery you can do:
if (confirm('Hide images?'))
{
$('img').remove();
}
Without jQuery you have to use getElemtentsByTag and a loop.
Related
I don't like lazy-loading because it looks quite ugly for the user in terms of UX. However, I understand the benefits (faster page load, low bandwidth, high PageSpeed scores etc.)
I am planning to write a javascript code which will:
Stay in the bottom > Wait for the page to fully load > After 3 seconds it will work > Force load all the images which were lazy-loaded previously during initial page load
With this, I won't lose any speed scores (because it will load as normal with lazy loaded images) But, also will load the full images when everything is done, so user won't notice. (we do the same for loading live chat scripts. It works pretty nice)
It will probably look something like this:
<script>
window.onload = function() {
setTimeout(function(){
var ForceLoadImages = document.createElement('script');
ForceLoadImages.type = 'text/javascript';
ForceLoadImages.src = 'link-to-the-script-to-force-load-images.js';
document.body.appendChild(chatScript);
}, 3000);
};
</script>
I am not a js expert. This was just a dummy example to give an idea. I am specifically asking how to write the content of that "link-to-the-script-to-force-load-images.js" part. Will appreciate any inputs.
There was a similar question here, but need an answer for Wordpress.
I guess that the wp lazy load uses data-src attribute to hold the image and when in view port, its adding the image to the src attribute.
Simplified like this:
<img data-src="URL"/>
*if its not like this, find in your source code the attribute where image is hold when out of view
What you need to do is select all images and change the data-src to src like this:
var images = document.querySelectorAll('img');
window.onload = function() {
setTimeout(function(){
for (var i=0; i<images.length; i++) {
if(images[i].getAttribute('data-src')) {
images[i].setAttribute('src',images[i].getAttribute('data-src'));
images[i].removeAttribute('data-src'); // optional if you need to remove data-src attribute after setting src
}
}
}, 3000);
};
<div class="container">
<img data-src='https://picsum.photos/id/237/200/300' />
<img data-src='https://picsum.photos/seed/picsum/200/300' />
<img data-src='https://picsum.photos/200/300' />
</div>
I just wanted to put the solution as an answer (thanks to kaize) who are looking for something like this. It is very clean and works nice:
<script>
var loadimages = document.querySelectorAll('img');
window.onload = function() {
setTimeout(function(){
//Force Load images
for (var i=0; i<loadimages.length; i++) {
if(loadimages[i].getAttribute('loading')) {
loadimages[i].removeAttribute('loading');
}
}
}, 3000);
};
</script>
Who is this for?
For those who does not like the user-experience of lazy loading images. But applying it due to PageSpeed scores.
Where to place this?
Place this to the bottom of your page.
What does this script do?
This script runs 3 seconds after the page loaded completely. It force-loads all the images which were waiting to get into the viewport to be lazy-loaded by removing the "loading" attribute. So that, you get good pagespeed scores for deferring image loads meanwhile keeping the user experience better. (Keep in mind that you lose the bandwidth advantage of lazy-loading concept)
I show links to 240 images on a page. The real images are uploaded by users. I tried to avoid showing an empty image if users did not upload it yet. jQuery did not work for me because of conflicts, so I have to do it in pure JavaScript.
image(s) links:
<img class="photo240" src="http://www.example.com/i/%%GLOBAL__AuthorID%%/p/b01.jpg" onerror="imgError()">
My JavaScript:
function imgError()
{
alert('The image could not be loaded.');
var _aryElm=document.getElementsByTagName('img'); //return an array with every <img> of the page
for( x in _aryElm) {
_elm=_aryElm[x];
_elm.className="photo240off";
}
}
The style photo240off equals to display:none.
Right now, whenever an image misses, all the images are turned to style photo240off and I want only the missing image to be hidden. So there is something wrong with my script.
(the overall script works well, because I get the alert).
Use this to get the image with the error.
Change to:
onerror="imgError(this)"
Then the function can be:
function imgError(el) {
alert('The image could not be loaded.');
el.className = "photo240off";
}
You need to reference the image from your onerror call and change the class only for that one.
Something like this:
HTML
<img class="photo240" src="example.jpg" onerror="imgError(this)">
JS
function imgError(el) {
el.className="photo240off";
}
I have the following script which take a string with html information (containing also reference to images).
When I create a DOM element the content for the image is being downloaded by the browser. I would like to know if it is possible to stop this Beauvoir and temporary prevent loading.
I am targeting web-kit and presto browsers.
relativeToAbosluteImgUrls: function(html, absoluteUrl) {
var tempDom = document.createElement('div');
debugger
tempDom.innerHTML = html;
var imgs = tempDom.getElementsByTagName('img'), i = imgs.length;
while (i--) {
var srcRel = imgs[i].getAttribute('src');
imgs[i].setAttribute('src', absoluteUrl + srcRel);
}
return tempDom.innerHTML;
},
Store the src path into an HTML5 data-* attribute such as data-src. Without src being set, the browser will not download any images. When you are ready to download the image, simply get the URL from the data-src attribute and set it as the src attribute
$(function() {
// Only modify the images that have 'data-src' attribute
$('img[data-src]').each(function(){
var src = $(this).data('src');
// modify src however you need to, maybe make
// a function called 'getAbsoluteUrl'
$(this).prop('src', src);
});
});
The approach taken by popular image library, Slimmage, is to wrap your img tags in noscript tags:
<noscript class="img">
<img src="my-image.jpeg" />
</noscript>
Web scrapers and people with JS turned off will see the image as if the noscript wasn't there but other browsers will completely ignore the noscript and img tags.
You can then use JavaScript to do whatever you want with it, for example (using jQuery):
$('noscript.img').replaceWith(function(){
return $(this.innerText).removeAttr('src');
});
I think you should reverse the logic, don't load the images by default and at the moment the image is needed, update it's src attribute to tell browser to start loading.
Or even better way would be to use some jquery lazy image loading plugin like this one:
http://www.appelsiini.net/projects/lazyload
Hope this helps.
To prevent images from being show, you could use this.
$(window).loaded( function() {
$("img").removeAttr("src");
});
It might be tricky and give unexpected results, but it does it.
I am looking for a way to cancel image loading using javascript. I've looked at other questions and hiding them is not enough. Also, the rest of the page must load (window.stop() is out of the question).
The page that is being loaded is not under my control, only one thing is guaranteed - the first <script> on the page is my javascript (lightweight - no jquery).
I have tried setting all img sources to nothing, that did not help since the dom is created after the page is parsed, and all browsers have the same behavior - the img is loaded once it is parsed.
Not possible with modern browsers. Even if you alter the src attribute of image tag with JavaScript browsers still insist on loading the images. I know this from developing the Lazy Load plugin.
The only way I can see to stop images loading is to not have an src attribute present in the image itself, and using a custom data-* attribute to hold the location of the image:
<img data-src="http://path.to/image.png" />
Obviously this doesn't gracefully degrade for those (admittedly rare) JavaScript disabled browsers, and therefore requires a noscript fall-back:
<img data-src="http://path.to/image.png" />
<noscript><img src="http://path.to/image.png" /></noscript>
And couple this with a simple function to load the images when you, or your users, are ready for them:
/* simple demo */
function imagePopulate(within, attr) {
within = within && within.nodeType == 1 ? within : document;
attr = attr || 'data-src';
var images = within.getElementsByTagName('img');
for (var i = 0, len = images.length; i < len; i++) {
if (images[i].parentNode.tagName.toLowerCase() !== 'noscript') {
images[i].src = images[i].getAttribute(attr);
}
}
}
document.getElementById('addImages').onclick = function(){
imagePopulate();
};
JS Fiddle demo.
I can't be sure for all browsers, but this seems to work in Chrome (in that there's no attempt, from looking at the network tab of the developer tools, to load the noscript-contained img).
It can be done with webworkers. See the following example:
https://github.com/NathanWalker/ng2-image-lazy-load.
Stopping a web worker cancels the image loading in browser
Recalling the onload event:
window.onload=function(){
imgs = document.getElementsByTagName('img');
for(i = 0; i < imgs.length(); i++){
imgs[i].src = '#';
}
};
If you want to only cancel the loading of the image , you can use sємsєм's solution
but i do not think it will work by using an window onload event .
You will probably need to provide a button to cancel the image load. Also i suggest, instead of setting the src attribute to "#" , you can remove the src attribute itself using
removeAttribute()
[Make sure you disable the cache while testing]
You need a proxy.
Your script can redirect to another server using something like
location.replace('http://yourserver.com/rewrite/php?url='+escape(this.href));
perhaps you tell us why you want to cancel image loading and whose site you are loading on so we can come up with a better solution
If there is nothing on the page other than images, you could try
document.write('<base href="http://yourserver.com/" />');
which will mess with all non-absolute src and hrefs on the page.
UPDATE Horrible hack but perhaps this almost pseudo code (I am off to bed) will do someting
document.write('<script src="jquery.js"></script><div id="myDiv"></div><!-'+'-');
$(function() {
$.get(location.href,function(data) {
$("#myDiv").html(data.replace(/src=/g,'xsrc='));
});
})
The closest you can get to what you maybe want is to have a quickly loaded placeholder image (ie. low resolution version of your image) and a hidden image (eg. {display:none}) in which the large image gets loaded but not displayed. Then in the onload event for the large image swap the images over (eg. display:block for the large image display:none for the smaller). I also use an array (with their url), to reuse any images that have already been opened.
BTW if you open an image in a new webpage when it gets closed then the image loading will be cancelled. So maybe you can do something similar in a webpage using an iframe to display the image.
To close the iframe and therefore unload the image, remove the frame from the DOM
(another advantage is that browsers spawn another process to deal with iframes, so the page won't lock up while the image loads)
I have a very complex page with a lot of scripts and a rather long loading time. On top of that page I want to implement the jquery Nivo Slider (http://nivo.dev7studios.com/).
In the documentation it says I have to list all images for the slider inside of a div#slider
<div id="slider">
<img src="images/slide1.jpg" alt="" />
<img src="images/slide2.jpg" alt="" title="#htmlcaption" />
<img src="images/slide3.jpg" alt="" title="This is an example of a caption" />
<img src="images/slide4.jpg" alt="" />
</div>
However I might have 10 images with a 1000x400px which is quite big. Those images would load when the page loads. Since they are in my header this might take quite a while.
I looking for a way to use any jquery Slider Plugin (like the nivo slider) but either dynamically load images or load all those images after everything else on my page has loaded.
Any idea how I could solve that?
Is there even a way to start a javascript process after everything else on the page has loaded? If there is a way I might have an solution for my problem (using the jquery ajax load() method) ... However I have no idea how to wait for everything else to load and then start the slider with all the images.
Here's what we did and its working great. We skipped setting src attribute of img and added img-location to a fake attribute lsrc. Then we load a dynamic image with lsrc value, and set the src of actual image only after its loaded.
Its not about faster loading, but its about showing the images only when its downloaded completely on your page, so that user do not have to see that annoying half-loaded images. A placeholder-image can be used while the actual images are being loaded.
Here's the code.
$(function(){
$.each(document.images, function(){
var this_image = this;
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
//this_image.src = options.loading; // show loading
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
var img = new Image();
img.src = lsrc;
$(img).load(function() {
this_image.src = this.src;
});
}
}
});
});
Edit: Trick is to set the src attribute only when that source is loaded in temporary img. $(img).load(fn); handles that.
In addition to Xhalent's answer, use the .append() function in jQuery to add them to the DOM:
Your HTML would just have:
<div id="slider">
</div>
And then your jquery would be:
jQuery(function(){
$("#slider").append('<img src="images/slide1.jpg" alt="" />');
});
check out jquery load() event, it waits for everything including graphics
$(window).load(function () {
// run code
});
on load you could then load the images using:
var image = new Image();
image.src = "/path/to/huge/file.jpg";
You can add a function onload to the image too
image.onload = function() {
...
}
I am using the below to power my slider and improve the page load performance.
for (var i = document.images.length - 1; i >= 0; i--) {
var this_image = document.images[i];
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
$(this_image).attr("src",lsrc);
}
}
}
the best way to use is b -lazy js.
bLazy is a lightweight lazy loading image script (less than 1.2KB minified and gzipped). It lets you lazy load and multi-serve your images so you can save bandwidth and server requests. The user will have faster load times and save data loaded if he/she doesn't browse the whole page.
For a full list of options, functions and examples go to the blog post: http://dinbror.dk/blog/blazy.
The following example is a lazy loading multi-serving responsive images example with a image callback :) If your device width is smaller than 420 px it'll serve a lighter and smaller version of the image. When an image has loaded it removes the loader in the callback.
In Html
<img class="b-lazy"
src="placeholder-image.jpg"
data-src="image.jpg"
data-src-small="small-image.jpg"
alt="Image description" />
In js
var bLazy = new Blazy({
breakpoints: [{
width: 420 // Max-width
, src: 'data-src-small'
}]
, success: function(element){
setTimeout(function(){
// We want to remove the loader gif now.
// First we find the parent container
// then we remove the "loading" class which holds the loader image
var parent = element.parentNode;
parent.className = parent.className.replace(/\bloading\b/,'');
}, 200);
}
});
Example
jquery has a syntax for executing javascript after document has loaded:
<script type="text/javascript">
jQuery(function(){
//your function implementation here...
});
</script>