Load image before anything else (render-blocking) - javascript

I have an image i want to load as the first thing when my page loads.
Currently i have an img tag with a src but it loads asynchronously, how can i assure the browser loads my image before rendering the page further?

A simple solution could be to use the preload attribute on <link>: Link types: preload. It is not a grantee that the content will be ready, as I read it, but maybe it fits your case.
Here is an example:
<head>
<link rel="preload" href="https://via.placeholder.com/450" as="image"/>
</head>
<body>
<img src="https://via.placeholder.com/450" />
</body>

I have done something similare ...
I have a 'splash screen' (you can use a simple white div to simulate no rendering ...)
Make a fetch to the img in js, then remove your splash screen ...
Fetch the img in js load the img in browser cache... so when your DOM display the img, she already in the browser cache ...

Related

How can I block images using js only?

I want to block all the images of any web page to lower the page loading time, consider the web page source code is loaded into browser but the documents/files still needed to be downloaded, is there any event to cover this problem?
I think can method must be followed in browsers text only mode.
No. If the src tag is already set the browser will Load the images no matter what. Remove the src tag after it was loaded doesn't change the fact that it was already downloaded.
The only way to avoid this is to set the src tags of imgs by Javascript dynamicly. And therefore not set images if you don't want to.
You can't make the browser not loading images if it's already in the html.
I'm not sure if it solves your problem but maybe you can try this:
<script type="text/javascript">
$(document).ready( function() { $("img").removeAttr("src"); } );
</script>
<div class="image"><img external-src="original.jpg" src="fake.jpg" /></div>
$(window).load(function(){
$('.image img').attr("src", $(this).attr('external-src')).removeAttr('external-src');
});
This will load all the images after whole dom loaded
You can remove the whole img tag
$("img").remove();
or you can just remove the image tag source attribute
$("img").removeAttr("src");
or you can just replace all the image source having shorter loading time
$("img").attr("src",'http://someimage.jpg');

Prevent iframe from loading on mobile

I am working on my portfolio page and I want to have my projects in a demo mode where the user can preview the sites in different viewports. I got the idea from here:
http://my.studiopress.com/themes/genesis/#demo-full
On mobile devices I would like to keep the iframes from loading, and instead have links to the projects open the sites in the new tab.
If I have the divs containing the iframes hidden at the very top of my CSS file with display:none, I can see the iframes still load in the background and the page takes a long time to load.
Is there any way to keep them from loading at all when on a certain device or viewport size?
You could achieve this by using JavaScript and the HTML Data-Attribut. By setting the src-Attribute to something like "#" it won't load anything. You can use the data-Attribute to store the URL for use with JavaScript.
<iframe src="#" data-src="https://placekitten.com/200/300" frameborder="0"></iframe>
Then you just check to screen size with window.matchMedia() and set the src-attribute at a specific screen size.
var $iframe = $('iframe'),
src = $iframe.data('src');
if (window.matchMedia("(min-width: 480px)").matches) {
$iframe.attr('src', src);
}
Here is a working example: https://jsfiddle.net/5LnjL3uc/
If you want to show the iframe after a user resizes the window you need to put your code into a function and bind it to a resize event:
var $iframe = $('iframe'),
src = $iframe.data('src');
function showIframe() {
if (window.matchMedia("(min-width: 480px)").matches) {
$iframe.attr('src', src);
}
}
$(window).on('resize', showIframe);
// Initialize it once on document ready
showIframe();
Working Example: https://jsfiddle.net/5LnjL3uc/1/
A better solution is to approach this in reverse.
IE do not load the src to begin with by placing your URL in a attribute like 'data-src' for example.
See my code for this below. You simply copy the data-src to your src when your device, or device width is not mobile/mobile size.
I believe this is the best solution because there are no uncertainties. With the previously mentioned solutions (which I tried) you are racing against the clock with the browser for when your code runs and it decides to load the iframe src.
if(device !== true) {
// add '#' to the href
let iframe = document.getElementById('3dExperience')
iframe.src = iframe.getAttribute('data-src')
}
Note: 'device' is the is-mobile npm package for detecting mobile.

How to prevent an <img> tag from loading its image?

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.

javascript to cancel image loading

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)

Javascript replace( ) function running more than once on the same image

I'm running a Javascript replace function to replace standard images with class="replace-2x"on my jQuery Mobile site with Retina-quality images if the user is on a mobile device with Retina display. For example, on a Retina device, logo.png will be replaced with logo#2x.png. The JS function is here:
function highdpi_init() {
$(".replace-2x").each(function () {
var src = $(this).attr("src");
$(this).attr("src", src.replace(".png", "#2x.png").replace(".jpg", "#2x.jpg"));
});
}
$(".page").live('pageinit',function(event){
highdpi_init();
});
I'm now running into an issue where the replace function is running more than once. So for example, it replaces logo.png with logo#2x.png as the page is loading, but then as the page continues to load, it KEEPS replacing .png with #2x.png in the img src over and over so that the image tag ends up looking like this:
<img src="mobile/images/logo#2x#2x#2x#2x#2x#2x#2x#2x#2x#2x#2x.png" class="replace-2x" alt="logo" width="200">
How can I prevent this from replacing on a single img element more than once? Keep in mind, I will have multiple images on the same page, so the function will need to apply to all images, but only one time each.
The problem is surely that your 'pageinit' event is being called more than once. You can either follow MДΓΓ БДLL's idea (which won't work if images are dynamically added) or you can make your handler smarter so that it doesn't replace the src if it already was replaced
function highdpi_init() {
$(".replace-2x").each(function () {
var $this = $(this);
var src = $this.attr("src");
$this.attr("src", src.replace(".png", "#2x.png").replace(".jpg", "#2x.jpg"));
// Remove the class so it doesn't replace it again
$this.removeClass('replace-2x')
});
}
You don't need JS for this, you could do it in CSS only.
<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" href="/css/highdpi.css"/>
You could make your images look like
<img src="transparent.gif" class="logo-a" alt="logo" width="200" />
And in highdpi.css you could do
img.logo-a {
background-image: url('file#2x.png')
}
And in lowdpi.css
img.logo-a {
background-image: url('file.png')
}
Using .one() should work since it is just a binding and if you are using Jquery Mobile the way that is suggested it will be just fine. That is unless you are passing back the html from the server. In which case it would be a good idea to add an extra condition to make sure that the src doesn't already have #2x.png before replacing.
There is disappointingly little documentation on pageinit on the offical jQuery Mobile docs. So I'm going to speculate here. It looks like pageinit is used to fire events for when a specific DOM element has finished loading, since it may not have been loaded on the initial page load (deferred until needed). That being said, it may be that adding/altering images to the DOM element in question fires the pageinit again. Could you tag each updated image with something that says, 'hey, I've already been updated to 2x'? Something such as
$.data(targetimg, 'retinafied', true);
And then check for that value before replacing the src?

Categories

Resources