Control load html with: new Image().src = HTML_URL - javascript

I am loading in browser cache next page with:
new Image().src = 'HTML_URL';
How do I control end of loading? If loading NOT an image -- always calling onerror.
I can't use jQuery.

Use onerror callback.
var image = new Image();
image.src = 'HTML_URL';
image.onerror = function () {
alert('I failed');
}

Related

Having an error in uploading file using js

When I am Uploading a file using the FileReader library the first time it's uploaded on the first click but the second time it is uploaded when I click on the button second time I am attaching a video link in which you can see the problem and attaching the code as well.
https://drive.google.com/file/d/1OzJLCA7URBcRy_5m_QVWAiLzo8l9eoqd/view
const imgPreviewing = (selected) => {
let img = myImgElement
if (selected.files && selected.files[0]) {
var reader = new FileReader();
reader.onload = function () {
let src = reader.result;
img.setAttribute("src", src);
};
reader.readAsDataURL(selected.files[0]);
}
};
Thank You.

Execute function only when images/sounds are loaded, Jquery

I dynamically set image and audio sources when window/document is already loaded, e.g. I set them after user performs some manipulations on the page:
// image and audio set
jQuery("#image").css('background-image', 'url(../content/icons/1/18.png)').css('backgroundPosition', '0 -40px');
var myAudio = new Audio('http://domain/content/audio/1/full-18.mp3');
myAudio.pause();
// i want this part of code be executed only when images and audio is fully loaded
myAudio.play();
Solution number 1, isn't working
jQuery("#page").load(function() {});
Solution number 2, isn't working
jQuery(window).load(function() {});
Any other idea how to this can be solved? Thank you in advance
You need to specifically target the image element to check if it has loaded.
$('#image').load(function () {
console.log('image loaded');
});
To check if the audio element is ready to be played you need to use onloadeddata.
var myAudio = new Audio('http://www.mfiles.co.uk/mp3-downloads/edvard-grieg-peer-gynt1-morning-mood.mp3');
myAudio.onloadeddata = audioIsLoaded();
function audioIsLoaded() {
console.log('audio is loaded');
}
Run the below code snippet to see this in action.
$('#image').load(function() {
alert('image loaded');
});
var myAudio = new Audio('http://www.mfiles.co.uk/mp3-downloads/edvard-grieg-peer-gynt1-morning-mood.mp3');
myAudio.onloadeddata = audioReady();
function audioReady() {
alert('audio ready');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="image" src="http://armpit-wrestling.com/wp-content/uploads/2016/06/bret-hart.jpg">

JS - readAsDataURL blocks browser activity

While I am loading a File into the browser I want to show an animated loading gif to the user. But if the file is very big the browser seems so buisy, that the animation of my gif does not work. What can I do to visualise the loading?
HTML
<img id="loader" src="img/load.gif" />
JS
reader.readAsDataURL(file);
reader.onloadend = function(){
document.getElementById('loader').style.display='none';
var source = reader.result;
document.getElementById('img').setAttribute( 'src', source);
}
document.getElementById('loader').style.display='block';
In theory, what you have should work, as the read operation is asynchronous. Maybe it's the onloadend callback that is blocking the execution. In any case, you could try this:
reader.onloadend = function(){
document.getElementById('loader').style.display='none';
var source = reader.result;
document.getElementById('img').setAttribute( 'src', source);
}
document.getElementById('loader').style.display='block';
// Make sure to start loading only after the loader was displayed
// (give the browser a chance to repaint)
setTimeout(function() {
reader.readAsDataURL(file);
}, 40);
The loaded event should be hooked first. Try this:
reader.onloadend = function(){
document.getElementById('loader').style.display='none';
var source = reader.result;
document.getElementById('img').setAttribute( 'src', source);
}
reader.readAsDataURL(file);
document.getElementById('loader').style.display='block';

Print PDF directly from JavaScript

I am building a list of PDFs in HTML. In the list I'd like to include a download link and a print button/link. Is there some way to directly open the Print dialog for the PDF without the user seeing the PDF or opening a PDF viewer?
Some variation of downloading the PDF into a hidden iframe and triggering it to print with JavaScript?
Based on comments below, it no longer works in modern browsers
This question demonstrates an approach that might be helpful to you: Silent print an embedded PDF
It uses the <embed> tag to embed the PDF in the document:
<embed
type="application/pdf"
src="path_to_pdf_document.pdf"
id="pdfDocument"
width="100%"
height="100%" />
Then you call the .print() method on the element in Javascript when the PDF is loaded:
function printDocument(documentId) {
var doc = document.getElementById(documentId);
//Wait until PDF is ready to print
if (typeof doc.print === 'undefined') {
setTimeout(function(){printDocument(documentId);}, 1000);
} else {
doc.print();
}
}
You could place the embed in a hidden iframe and print it from there, giving you a seamless experience.
Here is a function to print a PDF from an iframe.
You just need to pass the URL of the PDF to the function. It will create an iframe and trigger print once the PDF is load.
Note that the function doesn't destroy the iframe. Instead, it reuses it each time the function is call. It's hard to destroy the iframe because it is needed until the printing is done, and the print method doesn't has callback support (as far as I know).
printPdf = function (url) {
var iframe = this._printIframe;
if (!this._printIframe) {
iframe = this._printIframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.onload = function() {
setTimeout(function() {
iframe.focus();
iframe.contentWindow.print();
}, 1);
};
}
iframe.src = url;
}
You can use Print.js (npm install print-js). It's 128kB unpacked and you can find the docs at http://printjs.crabbly.com/.
It doesn't print on IE though, in those cases you'll have to download the PDF instead.
$http({
url: "",
method: "GET",
headers: {
"Content-type": "application/pdf"
},
responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
var pdfFile = new Blob([data], {
type: "application/pdf"
});
var pdfUrl = URL.createObjectURL(pdfFile);
//window.open(pdfUrl);
printJS(pdfUrl);
//var printwWindow = $window.open(pdfUrl);
//printwWindow.print();
}).error(function (data, status, headers, config) {
alert("Sorry, something went wrong")
});
https://github.com/mozilla/pdf.js/
for a live demo http://mozilla.github.io/pdf.js/
it's probably what you want, but I can't see the point of this since modern browsers include such functionality, also it will run terribly slow on low-powered devices like mobile devices that, by the way, have their own optimized plugins and apps.
Cross browser solution for printing pdf from base64 string:
Chrome: print window is opened
FF: new tab with pdf is opened
IE11: open/save prompt is opened
.
const blobPdfFromBase64String = base64String => {
const byteArray = Uint8Array.from(
atob(base64String)
.split('')
.map(char => char.charCodeAt(0))
);
return new Blob([byteArray], { type: 'application/pdf' });
};
const isIE11 = !!(window.navigator && window.navigator.msSaveOrOpenBlob); // or however you want to check it
const printPDF = blob => {
try {
isIE11
? window.navigator.msSaveOrOpenBlob(blob, 'documents.pdf')
: printJS(URL.createObjectURL(blob)); // http://printjs.crabbly.com/
} catch (e) {
throw PDFError;
}
};
printPDF(blobPdfFromBase64String(base64String))
BONUS - Opening blob file in new tab for IE11
If you're able to do some preprocessing of the base64 string on the server you could expose it under some url and use the link in printJS :)
I used this function to download pdf stream from server.
function printPdf(url) {
var iframe = document.createElement('iframe');
// iframe.id = 'pdfIframe'
iframe.className='pdfIframe'
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.onload = function () {
setTimeout(function () {
iframe.focus();
iframe.contentWindow.print();
URL.revokeObjectURL(url)
// document.body.removeChild(iframe)
}, 1);
};
iframe.src = url;
// URL.revokeObjectURL(url)
}
You can download the pdf file using fetch, and print it with Print.js
fetch("url").then(function (response) {
response.blob().then(function (blob) {
var reader = new FileReader();
reader.onload = function () {
//Remove the data:application/pdf;base64,
printJS({
printable: reader.result.substring(28),
type: 'pdf',
base64: true
});
};
reader.readAsDataURL(blob);
})
});
function printFile(url) {
const iframe = document.createElement('iframe');
iframe.src = url;
iframe.style.display = 'none';
document.body.appendChild(iframe);
// Use onload to make pdf preview work on firefox
iframe.onload = () => {
iframe.contentWindow.focus();
iframe.contentWindow.print();
};
}
It will be easy this way:
function PrintPdf (pdf) {
var iframe = document.createElement('iframe');
iframe.style.display = "none";
iframe.src = pdf;
document.body.appendChild(iframe);
iframe.contentWindow.focus();
iframe.contentWindow.print();
}
Simplification of #Nicolas BADIA's answer:
function printPDF (url)
{
let pdfFrame = document.body.appendChild(document.createElement('iframe'));
pdfFrame.style.display = 'none';
pdfFrame.onload = () => (void pdfFrame.contentWindow.print());
pdfFrame.src = url;
}

image onload event not firing

Should this work?
<script type=text/javascript>
function load_i () {
img = new Image();
img.onload = load_e();
img.src = "whatever.jpg";
}
function load_e() { alert("loaded"); }
</script>
Right now the image gets loaded, but apparently the onload event isn't being triggered.
Tried it in FF and Chrome.
change:
img.onload = load_e();
to:
img.onload = load_e;
With the following line:
img.onload = load_e();
You're calling load_e and assigning the result, undefined, to img.onload.

Categories