I need to load a file (either jpg or pdf) into a popup as a preview. The extension of the file is not given in the URL.
The point is that as long as it is an image the file need to exactly fit into the popup and because of that I'd like to output an image tag with the external file. If its a pdf I'd like to output an iframe (we are requiring the browser to have a pdf-plugin).
To achieve this i wrote the following code in jQuery:
var src = "http://localhost/test/js/embed/test";
var popup = $("#popup");
var previewImage = $('<img style="width:100%" id="previewImage" />');
var previewFrame = $('<iframe id="previewFrame"></iframe >');
previewFrame.on("load", function() {
//alert("frame loaded");
});
previewFrame.on("error", function() {
//alert("frame error");
});
previewImage.on("load", function() {
//alert("img loaded");
popup.append(previewImage);
});
previewImage.on("error", function() {
//alert("img error");
previewFrame.attr("src", src);
popup.append(previewFrame);
});
previewImage.attr("src", src);
Looking at the inspector i can see that, as long as a pdf is loaded, 2 requests are made for the file. Can I somehow change the code so that always only one request is made or are the 2 requests an issue anyway (will the second request take the file from the cache)?
Thanks in advance
Related
I am trying to import photos from a local file on my computer to my HTML file. I have managed to do this but I need to speed up the time it takes to load in on the page, 2.4mins. My idea was to load a smaller file size of the image, 200px by 200px and then load the full-sized image in the background. The problem that I am encountering is that I am not able to integrate my code of loading the images from a local file with the lazy loading code. can anyone help?
const $spans = $("span");
const {
length
} = $spans;
$spans.each(function(i) {
$(this).append("<img src='Images/With Out Logo/Insta Photo-" + (length - i) + ".JPG' />");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<span class="Images"></span>
I'd look into using intersection observerAPI for lazy loading images, there's an excellent Google Developer Guide on this whole subject.
A basic example of this is:
Alter your <img> tags to add:
data-src
data-srcset
These point to the image to load once the element is being looked at in the "viewport".
Example:
<img class="lazy" src="placeholder.jpg" data-src="lazy-img-1x.jpg" data-srcset="lazy-img-1x.jpg 1x">
Then in a <script> tag or wherever you run your page's code just have a function that listens for the DOMContentLoaded event:
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
if ("IntersectionObserver" in window) {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.srcset = lazyImage.dataset.srcset;
lazyImage.classList.remove("lazy");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// Possibly fall back to a more compatible method here
}
});
Here's a CodePen from the guide with a better example.
Before you upload images for use on a website, you should optimize them first to prevent slow load time/your current issue.
As your images are seemingly stored in a local folder, I would suggest to first, make a back-up of the folder containing the images [to an external hard drive or another area of your hard drive].
Then, visit an image compression site (such as tinypng, - I use this but there are others, e.g CompressJpeg) Compressing images will greatly reduce the file size but the images will appear the same. You can upload multiple images at a time, and download bundles of compressed images as a zip. Ensure that when you extract the images, that they are named as you would like (and that they don't have a '1' at the end [as usually added, to indicate that the file is a copy/2nd version])
When you run your code using the smaller images, you should find that your processing time is reduced substantially.
Hope this helps
A sidenote - Both the afore-mentioned websites handle both jpgs and png formats - the website names can be misleading! :)
I have this line of HTML in my code:
<img src="https://mundonewimpact.com.br/wp-content/uploads/2018/10/MNI-Logo-3.png" id="site-logo" alt="Mundo New Impact">
and what I want to do is that, everytime an user loads any page from my website, this img loads a .gif file (which is: https://im3.ezgif.com/tmp/ezgif-3-d8b13ba46bfb.gif) for a couple of seconds, enough for its animation to finish, and then replace this .gif file to the original .png file.
I tried using this piece of javascript code, but it doesn't work:
function play(){
var img = document.getElementById("site-logo");
if (img.src = "https://mundonewimpact.com.br/wp-content/uploads/2018/10/MNI-Logo-3.png"){
img.src = "https://im3.ezgif.com/tmp/ezgif-3-d8b13ba46bfb.gif";
}else{
img.src = "https://mundonewimpact.com.br/wp-content/uploads/2018/10/MNI-Logo-3.png";
}
setTimeout(function(){end()},10000);
}
function end(){
document.getElementById("site-logo").src = "https://mundonewimpact.com.br/wp-content/uploads/2018/10/MNI-Logo-3.png";
}
What am I doing wrong? I am a total noob so help me please!
You need to call play()in order to run the function.
You also have mistakes like if (img.src = ... instead of if (img.src == ....
I would work with event handlers, like, show the GIF animation and when the document ready event triggers, change the GIF to a different image.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var img = document.getElementById("site-logo");
img.src = "https://mundonewimpact.com.br/wp-content/uploads/2018/10/MNI-Logo-3.png";
});
</script>
How can I change my image url to CDN URL using JavaScript or jQuery
For example urls in my webpage are
https://example.com/img/img.jpg
Then it should be replaced by
https://mycdn.com/https://example.com/img/img.jpg
Consider following snippet:
$('img').each(function(){
var img = $(this);
var srcOld = img.attr('src');
var srcNew = 'https://mycdn.com/' + srcOld;
img.attr('src', srcNew); // Updating src here
});
Explanation: The above snippet loops to each img element and updates
src of each one. Whereas this way HTML page will load all images twice
first for local images and then CDN images. Better way to update src
from backend.
I want to load two images in a single <img /> tag. First small image will be shown by src attribute and second large image will be inside data-src attribute but one image will be shown at once, that will be in src attribute. I want when page load small image will be load and show first and after completing loading of large image in the background it will be replaced by small image so that we can see large image. I have the code that will take large image from data-src attribute and place large image in src attribute.
$(document).ready(function(){
$("#image4").load(function(){
var imgDefer = document.getElementsByTagName('img');
for (var i=0; i<imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
} }
});
});
I want to do this because I don't want to wait for long time to load large image, instead I want to see the small image first. I am facing the problem when page load, it's loading small and large images in parallel. For your information images have the drag and zoom functionality.
Current live code is here: http://virtualepark.com/new1/demo.html
The code you posted here is not deployed on your server - there is some other stuff using the mousewheel-event.
Try loading the big image hidden in the background and once its loaded, set the url of the visible image:
//get all images
$('img').each(function(i, img) {
var img = $(img);
//if they have a data-src
if(img.attr('data-src')) {
//register for the load-event for the initial image
img.one('load', function() {
//if small image is loaded, begin loading the big image
//create new hidden image
var hiddenImg = new Image();
hiddenImg.onload = function() {
//if the hidden image is loaded, set the src-attribute of the
//real image (it will show instantly)
img.attr('src', img.attr('data-src'));
};
//trigger loading of the resource
hiddenImg.src = img.attr('data-src');
});
});
});
(credits to Load image from url and draw to HTML5 Canvas)
you can load to hidden tag and after load complet change them.
you can try to start the loading after the image is loaded.
$('img').load(function(){
var bigImgSrc = $(this).data('src');
var img = $(this);
if(bigImgSrc != img.prop('src')){
var bigImg =$('<img>').prop('src', bigImgSrc);
bigImg.load(function(){
img.prop('src', bigImgSrc);
});
}
});
I'm not 100% sure if you need to append the bigImg to the DOM or if it also loads like this. If you need to add it to the DOM use bigImg.hide().appendTo('body') and then use the remove funtion when loaded.
You should also be aware that the load-function not work in all cases, see https://api.jquery.com/load-event/
edit there was in an infinity loop in the prev. code example
<!--WunderGroundRadar-->
<script type = "text/javascript">
setInterval(function refreshRadar() {
document.getElementById("content14").src = "http://api.wunderground.com/api/MyAPIkey/animatedradar/q/autoip.gif?&radius=90&num=15&delay=20&width=430&height=500&smooth=1&newmaps=1&interval=15&rainsnow=1"
}, 900000);
</script>
I use the code above to refresh a weather radar .gif image on my website about every 15 minutes. This normally works great, but sometimes when the refresh takes place the image is broken from it's source and my site has a broken image icon until the next refresh takes place approx. 15 minutes later. I would like to set this up so that if the requested image is broken or not available at the time that the refresh function runs, I keep the image that is already loaded instead of replacing it with a broken image icon. I am willing to use any javascript or Jquery that might achieve this, but I am a novice programmer, so if you could break down any intricate code that would be much appreciated. Thanks!
You can try something like this
<script type = "text/javascript">
setInterval(function refreshRadar() {
img = new Image();
img.onload = function(){
document.getElementById("content14").src = img.src;
};
img.src = "http://api.wunderground.com/api/MyAPIkey/animatedradar/q/autoip.gif?&radius=90&num=15&delay=20&width=430&height=500&smooth=1&newmaps=1&interval=15&rainsnow=1"
}, 900000);
</script>
it attempts to load source to a temporary image and only on successful load assings source to "content14"