I'm trying to make drag n' drop upload file in JS. I've written code as follow:
<div id="drop_zone">
<div style="clear: both"></div>
</div>
<output id="list"></output>
<script type="text/javascript">
var Vector = function() {
var _array = [];
this.add = function(item) {
_array.push(item);
};
this.delete = function(index) {
_array.splice(index, 1);
};
this.foreach = function(callback) {
for(i=0; i<_array.length; i++) {
callback(_array[i]);
}
};
this.length = function() {
return _array.length;
};
this.clear = function() {
_array = [];
};
};
var Snap = function(args) {
this.name = args.name || null;
this.type = args.type || null;
this.size = args.size || null;
this.modified = args.modified || null;
this.source = args.source || null;
}
var images = new Vector();
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
if(files.length != 0) {
for(var i=0, f; f = files[i]; i++) {
var image = new Snap({
name : escape(f.name),
type : f.type||'n/a',
size : f.size,
modified : f.lastModifiedDate ? f.lastModifiedDate.toLocaleString() : 'n/a'
});
var file = files[i];
var filereader = new FileReader;
filereader.onload = function(e) {
image.source = this.result;
};
filereader.readAsDataURL(file);
images.add(image);
}
}
alert(images.length());
render();
}
function render() {
var list = document.getElementById('list');
images.foreach(function(elem) {
var div = document.createElement('div');
var divtext = elem.name + '(<i>' + elem.type + '</i>), ' + elem.size + ' <small>[' + elem.modified + ']</small>';
div.innerHTML = divtext;
list.appendChild(div);
var img = document.createElement('img');
img.src = elem.source;
document.getElementById('drop_zone').appendChild(img);
});
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy';
}
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
</script>
It's not working as I wish.
This view is after I drag image first time. images.length = 1
This view is after I drag image second time. images.length actually = 2, not 3, so Vector images works as it is supposed to work.
View after third dragging, one and the same image. images.length = 3, not 6, so when it comes to Vector, it's ok.
I haven't no idea how to make it works.
Thanks in advance.
Related
I have this record.js script to toggle a recording that is currently working as expected.
function Record_Current(config) {
config = config || {};
var self = this;
var audioInput;
var audioNode;
var bufferSize = config.bufferSize || 4096;
var recordedData = [];
var recording = false;
var recordingLength = 0;
var startDate;
var audioCtx;
this.toggleRecording = function() {
if (recording) {
self.stop();
} else {
self.start();
}
};
this.start = function() {
// reset any previous data
recordedData = [];
recordingLength = 0;
// webkit audio context shim
audioCtx = new(window.AudioContext || window.webkitAudioContext)();
if (audioCtx.createJavaScriptNode) {
audioNode = audioCtx.createJavaScriptNode(bufferSize, 1, 1);
} else if (audioCtx.createScriptProcessor) {
audioNode = audioCtx.createScriptProcessor(bufferSize, 1, 1);
} else {
throw 'WebAudio not supported!';
}
audioNode.connect(audioCtx.destination);
navigator.mediaDevices.getUserMedia({ audio: true })
.then(onMicrophoneCaptured)
.catch(onMicrophoneError);
};
this.stop = function() {
stopRecording(function(blob) {
self.blob = blob;
config.onRecordingStop && config.onRecordingStop(blob);
});
};
this.upload = function(url, params, callback) {
var formData = new FormData();
formData.append("audio", self.blob, config.filename || 'recording.wav');
for (var i in params)
formData.append(i, params[i]);
var request = new XMLHttpRequest();
request.upload.addEventListener("progress", function(e) {
callback('progress', e, request);
});
request.upload.addEventListener("load", function(e) {
callback('load', e, request);
});
request.onreadystatechange = function(e) {
var status = 'loading';
if (request.readyState === 4) {
status = request.status === 200 ? 'done' : 'error';
}
callback(status, e, request);
};
request.open("POST", url);
request.send(formData);
};
function stopRecording(callback) {
// stop recording
recording = false;
// to make sure onaudioprocess stops firing
window.localStream.getTracks().forEach((track) => { track.stop(); });
audioInput.disconnect();
audioNode.disconnect();
exportWav({
sampleRate: sampleRate,
recordingLength: recordingLength,
data: recordedData
}, function(buffer, view) {
self.blob = new Blob([view], { type: 'audio/wav' });
callback && callback(self.blob);
});
}
function onMicrophoneCaptured(microphone) {
if (config.visualizer)
visualize(microphone);
// save the stream so we can disconnect it when we're done
window.localStream = microphone;
audioInput = audioCtx.createMediaStreamSource(microphone);
audioInput.connect(audioNode);
audioNode.onaudioprocess = onAudioProcess;
recording = true;
self.startDate = new Date();
config.onRecordingStart && config.onRecordingStart();
sampleRate = audioCtx.sampleRate;
}
function onMicrophoneError(e) {
console.log(e);
alert('Unable to access the microphone.');
}
function onAudioProcess(e) {
if (!recording) {
return;
}
recordedData.push(new Float32Array(e.inputBuffer.getChannelData(0)));
recordingLength += bufferSize;
self.recordingLength = recordingLength;
self.duration = new Date().getTime() - self.startDate.getTime();
config.onRecording && config.onRecording(self.duration);
}
function visualize(stream) {
var canvas = config.visualizer.element;
if (!canvas)
return;
var canvasCtx = canvas.getContext("2d");
var source = audioCtx.createMediaStreamSource(stream);
var analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
source.connect(analyser);
function draw() {
// get the canvas dimensions
var width = canvas.width,
height = canvas.height;
// ask the browser to schedule a redraw before the next repaint
requestAnimationFrame(draw);
// clear the canvas
canvasCtx.fillStyle = config.visualizer.backcolor || '#fff';
canvasCtx.fillRect(0, 0, width, height);
if (!recording)
return;
canvasCtx.lineWidth = config.visualizer.linewidth || 2;
canvasCtx.strokeStyle = config.visualizer.forecolor || '#f00';
canvasCtx.beginPath();
var sliceWidth = width * 1.0 / bufferLength;
var x = 0;
analyser.getByteTimeDomainData(dataArray);
for (var i = 0; i < bufferLength; i++) {
var v = dataArray[i] / 128.0;
var y = v * height / 2;
i === 0 ? canvasCtx.moveTo(x, y) : canvasCtx.lineTo(x, y);
x += sliceWidth;
}
canvasCtx.lineTo(canvas.width, canvas.height / 2);
canvasCtx.stroke();
}
draw();
}
function exportWav(config, callback) {
function inlineWebWorker(config, cb) {
var data = config.data.slice(0);
var sampleRate = config.sampleRate;
data = joinBuffers(data, config.recordingLength);
console.log(data);
function joinBuffers(channelBuffer, count) {
var result = new Float64Array(count);
var offset = 0;
var lng = channelBuffer.length;
for (var i = 0; i < lng; i++) {
var buffer = channelBuffer[i];
result.set(buffer, offset);
offset += buffer.length;
}
return result;
}
function writeUTFBytes(view, offset, string) {
var lng = string.length;
for (var i = 0; i < lng; i++) {
view.setUint8(offset + i, string.charCodeAt(i));
}
}
var dataLength = data.length;
// create wav file
var buffer = new ArrayBuffer(44 + dataLength * 2);
var view = new DataView(buffer);
writeUTFBytes(view, 0, 'RIFF'); // RIFF chunk descriptor/identifier
view.setUint32(4, 44 + dataLength * 2, true); // RIFF chunk length
writeUTFBytes(view, 8, 'WAVE'); // RIFF type
writeUTFBytes(view, 12, 'fmt '); // format chunk identifier, FMT sub-chunk
view.setUint32(16, 16, true); // format chunk length
view.setUint16(20, 1, true); // sample format (raw)
view.setUint16(22, 1, true); // mono (1 channel)
view.setUint32(24, sampleRate, true); // sample rate
view.setUint32(28, sampleRate * 2, true); // byte rate (sample rate * block align)
view.setUint16(32, 2, true); // block align (channel count * bytes per sample)
view.setUint16(34, 16, true); // bits per sample
writeUTFBytes(view, 36, 'data'); // data sub-chunk identifier
view.setUint32(40, dataLength * 2, true); // data chunk length
// write the PCM samples
var index = 44;
for (var i = 0; i < dataLength; i++) {
view.setInt16(index, data[i] * 0x7FFF, true);
index += 2;
}
if (cb) {
return cb({
buffer: buffer,
view: view
});
}
postMessage({
buffer: buffer,
view: view
});
}
var webWorker = processInWebWorker(inlineWebWorker);
webWorker.onmessage = function(event) {
callback(event.data.buffer, event.data.view);
// release memory
URL.revokeObjectURL(webWorker.workerURL);
};
webWorker.postMessage(config);
}
function processInWebWorker(_function) {
var workerURL = URL.createObjectURL(new Blob([_function.toString(),
';this.onmessage = function (e) {' + _function.name + '(e.data);}'
], {
type: 'application/javascript'
}));
var worker = new Worker(workerURL);
worker.workerURL = workerURL;
console.log(worker);
return worker;
}
function renderRecording(workerURL, list) {
const worker_url = URL.createObjectURL(workerURL);
const li = document.createElement('li');
const audio = document.createElement('audio');
const anchor = document.createElement('a');
anchor.setAttribute('href', workerURL);
const now = new Date();
anchor.setAttribute(
'download',
`recording-${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDay().toString().padStart(2, '0')}--${now.getHours().toString().padStart(2, '0')}-${now.getMinutes().toString().padStart(2, '0')}-${now.getSeconds().toString().padStart(2, '0')}.webm`
);
anchor.innerText = 'Download';
audio.setAttribute('src', worker_url);
audio.setAttribute('controls', 'controls');
li.appendChild(audio);
li.appendChild(anchor);
list.appendChild(li);
}
}
and this Google Drive Script
var driveLink = require('stream');
module.exports.uploadFile = function(req) {
var file;
console.log("driveApi upload reached")
function blobToFile(req) {
file = req.body.blob
file.lastModifiedDate = new Date();
file.name = req.body.word;
return file;
}
var bufStream = new stream.PassThrough();
bufStream.end(file);
console.log(typeof 42);
var folderId = "Folder"; // Enter Folder Name
var fileMetadata = {
"name": req.body.word,
parents: [folderId]
}
var media = {
mimeType: "audio/mp3",
body: bufStream
}
drive.files.create({
auth: jwToken,
resource: fileMetadata,
media: media,
fields: "id"
}, function(err, file) {
if (err) {
console.error(err);
} else {
console.log("File Id: ", file.id);
}
console.log("driveApi upload accomplished")
});
}
I have tried a few different approaches to combining the two to make it so it automatically saves the .wav file to the Drive API but it does not work.
I believe I am either not merging the two scripts together the right way or I am missing something. Do I need to use V3 of the Google API?
If anyone could provide some guidance on how to merge the two properly that would be greatly appreciated. Thank you!
I have these codes to display the names of the files selected from input and it will preview the FIRST image:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var filename = input.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var files = $('#my_file')[0].files;
for (var i = 0; i < files.length; i++) {
$("#files").append('<div class="filename"><span name="fileNameList">'+files[i].name+'</span></div>');
}
$("#nextBtn").on("click",function(){
})
$('#myImg').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
What i want to do is that when i click on the "next" button,it will go to the next image selected or if i click on the "prev" button,it will go to the previous image(the last image if im displaying the first one).How do i go about doing this?Thank You.
UPDATE:
var fileInput = document.getElementById("my_file");
$(fileInput).on("change",function(event){
var next = document.getElementById("nextBtn");
next.onclick = function(xFlip){
curImage = curImage+xFlip;
var files = event.target.files;
if(curImage > files.length){
curImage = 1;
}
if(curImage == 0){
curImage = files.length;
}
$("#myImg").attr('src',files[curImage-1]);
};
console.log(document.getElementById("myImg").getAttribute("src"));
});
I did it this way as the images are retrieved from input type file multiple.
https://jsfiddle.net/bfr6wp7e/2/
Thanks for the challenge, it was my first meeting with the File API :)
Here is the jsFiddle with what I believe is the correct answer to your question:
https://jsfiddle.net/mkbctrll/aq9Laaew/300936/
JS part
const fileInupt = document.getElementById('fileInput')
const fileList = document.getElementById('fileList')
const slickSettings = {
infinite: true,
speed: 300,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true
}
const initSlickCarousel = (target, settings) => {
$(target).slick(settings);
}
const handleInputChange = (event) => {
console.log('We are handling it sir!')
const filesArray = Array.from(event.target.files)
filesArray.map((singleFile) => {
const outputImg = document.createElement('img')
const fileReader = new FileReader()
outputImg.className = 'img-thumbnail'
// Let's read it as data url - onload won't return a thing without it
fileReader.readAsDataURL(singleFile)
fileReader.onload = (event) => { outputImg.src = event.target.result }
console.log(outputImg)
fileList.appendChild(outputImg)
})
initSlickCarousel(fileList, slickSettings)
}
if(window.File && window.FileReader && window.FileList) { // check if browser can handle this
console.log('We are good to go sir!')
fileInput.addEventListener('change', handleInputChange, false)
} else {
alert('File features are not fully supported. Please consider changing the browser (newest Chrome or Mozilla).')
}
Though it won't be possible for me to get a grasp on that tech if not for the following sources:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onload
Sample code for Prev and Next image slide.
var numImages = 4;
var curImage = 1;
var imgArray =[
"one.jpg",
"two.jpg",
"three.jpg",
"four.jpg"
];
function imageShow( xflip ) {
curImage = curImage + xflip;
if (curImage > numImages)
{ curImage = 1 ; }
if (curImage == 0)
{ curImage = numImages ; }
document.images[2].src = imgArray[curImage - 1];
}
HTML buttons:
<input type="button" value="<< Prev" onclick="imageShow(-1)">
<input type="button" value="Next >>" onclick="imageShow(1)">
I am trying to Sort files I pull from File Explorer by name, they sort by when they load, how would I sort them by name instead using my code below?
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
}
}
// output file information
function ParseFile(file) {
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p align=center><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '"></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
submitbutton.style.display = "none";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
This code drags and drops the Files in my program and loads them, but does not sort in alphabetical, what would be the best way to sort them with my code below?
var files;
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
}
}
// output file information
function ParseFile(file) {
// display an image
var basename = file.name.substring(0,file.name.length-4);
files.push("<div style=\"width: 100%; overflow: hidden;\"><div style=\"width: 600px; float: left;\">" +
"<strong>" + basename + ".pdf:</strong><br />" +
'<iframe src="\\\\sovarchpri01\\d$\\1000Sunrise\\Process\\stage\\' + basename +".pdf#view=fit" + '"height="75%" width="500px"></iframe></p>' +
"</div><div style=\"margin-left: 620px;\">" +
"<strong>" + basename + ".png:</strong><br />" +
"<img src=\"\\\\sovarchpri01\\d$\\Fleissner\\ORG_5535_Documents\\" + basename + ".png\" height=\"75%\" width=\"500px\">" +
"</div> ");
}
function sortFiles() {
files.sort().reverse();
for (var i = 0; i < files.length; ++i) {
Output(files[i]);
}
}
function resetWindow(){
window.location.reload(true)
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton"),
sortbutton = $id("sortbutton"),
resetbutton = $id("resetbutton")
resetbutton2 = $id("resetbutton2");;
files = new Array();
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
submitbutton.addEventListener("click", sortFiles , false); //style.display = "none";
sortbutton.addEventListener("click", sortFiles , false);
resetbutton.addEventListener("click", resetWindow , false);
resetbutton2.addEventListener("click", resetWindow , false);
}
}
// call initialization file
if (window.FileReader) {
Init();
}
})();
I'm trying to get all not loaded elements in a webpage by including a script in the head of the index.html but I've some problems.
This is the code:
document.addEventListener('DOMContentLoaded', function () {
console.log("here");
var scripts = document.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++){
scripts[i].onerror =function(message, source, lineno) {
console.log("JS: Error SCRIPT");
}
}
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
imgs[i].onerror =function(message, source, lineno) {
console.log("JS: Error IMG ");
}
}
var links = document.getElementsByTagName('link');
for(var i=0;i<links.length;i++){
links[i].onerror = function(message, source, lineno){
console.log("JS: Error CSS ");
}
}
});
I put 3 wrong CSS, Images and Scripts (they don't exist as resources) inside the HTML file where I call the script.
When I run locally the index.html I get "Error IMG" and "Error CSS".
When I run on the server I get only "Error IMG".
In both cases, I don't get "Error SCRIPT".
What I'm doing wrong?
UPDATE: This is the code
appmetrics.js
//class that store page resource data
/*
ES6
class Resource{
constructor(name,type,start,end,duration){
this.name = name;
this.type = type;
this.start = start;
this.end = end;
this.duration = duration;
}
}
*/
function Resource (name,type,start,end,duration){
this.name = name;
this.type = type;
this.start = start;
this.end = end;
this.duration = duration;
}
/*
ES6
class Errors{
constructor(name,source,line){
this.name = name;
this.source = source;
this.line = line;
}
}
*/
function Errors(name,source,line){
this.name = name;
this.source = source;
this.line = line;
}
//endpoint to send data
var endpoint = "https://requestb.in/sr8wnnsr"
var resources = Array();
var errors = Array();
var pageLoadTime;
var start = performance.now();
window.onload = function(){
pageLoadTime = performance.now()-start;
console.log("Page loading time: " + pageLoadTime);
//getting page resources and pushing them into the array
var res = performance.getEntriesByType("resource");
res.forEach(function add(item){
resources.push(new Resource(item.name,item.initiatorType,item.startTime,item.responseEnd,item.duration));
})
console.log(resources);
var jsonRes = JSON.stringify(resources);
//sendMetricToEndpoint(jsonRes);
//sendMetricToEndpoint(pageLoadTime.toString());
}
window.onerror = function(message, source, lineno) {
console.log("Error detected!" + "\nMessage: " +message +"\nSource: "+ source +"\nLine: "+ lineno);
errors.push(new Errors(message,source,lineno));
console.log(errors);
}
//Not working code
/*
document.addEventListener('DOMContentLoaded', function () {
console.log("here");
var scripts = document.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++){
scripts[i].onerror =function(message, source, lineno) {
console.log("JS: Errore SCRIPT");
}
}
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
imgs[i].onerror =function(message, source, lineno) {
console.log("JS: Errore IMG ");
}
}
var links = document.getElementsByTagName('link');
for(var i=0;i<links.length;i++){
links[i].onerror = function(message, source, lineno){
console.log("JS: Errore CSS ");
}
}
});
*/
//StackOverflow solution start
var scripts = [];
for (var i = 0, nodes = document.getElementsByTagName('script'); i < nodes.length; i++) {
scripts[i] = { source: nodes[i].src, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = scripts.findIndex(function(script) {
return script.source === loadedNode.src;
});
scripts[index].loaded = true;
};
}
var links = [];
for (var i = 0, nodes = document.getElementsByTagName('link'); i < nodes.length; i++) {
links[i] = { source: nodes[i].href, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = links.findIndex(function(link) {
link.href === loadedNode.href;
});
links[index].loaded = true;
};
}
document.addEventListener('DOMContentLoaded', function() {
console.log("here");
scripts.filter(function(script) {
return !script.loaded;
}).forEach(function(script) {
console.log("Error loading script: " + script.source);
});
links.filter(function(link) {
return !link.loaded;
}).forEach(function(link) {
console.log("Error loading link: " + link.source);
});
// and the rest of the elements
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].onerror = function() {
console.log("Error loading image: " + this.src);
};
}
});
//StackOverflow solution stop
/**
* Function that send metric to endpoint.
*
* #param {string} endpoint Where to send data.
* #param {*} data data to send (JSON or string)
*/
function sendMetricToEndpoint(data){
console.log("Sending metrics to endpoint");
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
};
xhttp.open("POST", endpoint, true);
//xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(data);
}
index.html
<html>
<head>
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>-->
<script src="js/appmetricsmod.js"></script>
<link rel="stylesheet" href="styletests.css">
<link rel="stylesheet" href="styletestss.css">
<link rel="stylesheet" href="styletestsss.css">
<script src="js/error1.js"></script>
<script src="js/error2.js"></script>
<script src="js/error3.js"></script>
</head>
<body>
<img src="imgtest.png"></img>
<img src="imgErr1.png"></img>
<img src="imgErr2.png"></img>
<img src="imgErr3.png"></img>
<img src="http://images.centrometeoitaliano.it/wp-content/uploads/2016/11/15/l1.jpg"></img>
<div class="divtest">
hello this is a test
</div>
<script>
</script>
</body>
</html>
Sadly, you you cannot get link nor script error load with onerror event, but you can handle the loaded content, and filter which were not loaded. This is possible with the load event for the link and script tags.
var scripts = [];
for (var i = 0, nodes = document.getElementsByTagName('script'); i < nodes.length; i++) {
scripts[i] = { source: nodes[i].src, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = scripts.findIndex(function(script) {
return script.source === loadedNode.src;
});
scripts[index].loaded = true;
};
}
var links = [];
for (var i = 0, nodes = document.getElementsByTagName('link'); i < nodes.length; i++) {
links[i] = { source: nodes[i].href, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = links.findIndex(function(link) {
link.href === loadedNode.href;
});
links[index].loaded = true;
};
}
document.addEventListener('DOMContentLoaded', function() {
console.log("here");
scripts.filter(function(script) {
return !script.loaded;
}).forEach(function(script) {
console.log("Error loading script: " + script.source);
});
links.filter(function(link) {
return !link.loaded;
}).forEach(function(link) {
console.log("Error loading link: " + link.source);
});
// and the rest of the elements
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].onerror = function() {
console.log("Error loading image: " + this.src);
};
}
});
Hope it helps :)
Using the classes Resources and Errors above, I solved the problem by taking all the resources of the page and then removing the working ones. The result is an array of not loaded resources.
This is the code:
var res = performance.getEntriesByType("resource");
res.forEach(function add(item){
resources.push(new Resource(item.name,
item.initiatorType,
item.startTime,
item.responseEnd,
item.duration));
})
var flag = true;
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
for(var j=0;j<resources.length;j++){
if(imgs[i].src == resources[j].name){
flag = false;
}
}
if(flag && imgs[i].src){
errors.push(new Errors("RES NOT FOUND",imgs[i].src,null));
}
flag = true;
}
var scripts = document.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++){
for(var j=0;j<resources.length;j++){
if(scripts[i].src == resources[j].name){
flag = false;
}
}
if(flag && scripts[i].src){
errors.push(new Errors("RES NOT FOUND",scripts[i].src,null));
}
flag = true;
}
var links = document.getElementsByTagName('link');
for(var i=0;i<links.length;i++){
for(var j=0;j<resources.length;j++){
if(links[i].src == resources[j].name){
flag = false;
}
}
if(flag && links[i].href){
errors.push(new Errors("RES NOT FOUND",links[i].href,null));
}
flag = true;
}
console.log(resources);
console.log(errors);
I am working on around 40 Large images each of size 9000KB.
i have below code ,all images are loading at a time which makes my screen to freeze,I want that my control will wait until the first image is successfully progress then loads completely then move on to the next one.any idea is helpful..
//dropping around 40 images
dropbox.addEventListener("drop", dropUpload, false);
function dropUpload(event) {
noop(event);
var dropMethod = event.dataTransfer;
var classicMethod = event.target;
var dropedFiles = (dropMethod == undefined) ? classicMethod.files: dropMethod.files;
for ( var i = 0; i < dropedFiles.length; i++) {
addFilesToUpload(dropedFiles[i]);
}
}
function addFilesToUpload(file) {
var li = document.createElement("li"), div = document.createElement("div"), img, progressBarContainer = document
.createElement("div"), progressBar = document.createElement("div"), tBody;
li.appendChild(div);
progressBarContainer.className = "progress-bar-container";
progressBar.className = "progress-bar";
progressBar.setAttribute("id", "proBar_" + (indexN++));
progressBarContainer.appendChild(progressBar);
li.appendChild(progressBarContainer);
var reader = new FileReader();
reader.onerror = function(event) {
alert("couldn't read file " + event.target.error.code);
};
// Present file info and append it to the list of files
fileInfo = "<div><strong>Name:</strong> " + file.name + "</div>";
fileInfo += "<div><strong>Size:</strong> " + parseInt(file.size / 1024, 10)
+ " kb</div>";
fileInfo += "<div><strong>Type:</strong> " + file.type + "</div>";
div.innerHTML = fileInfo;
if (reader !== "undefined" && (/image/i).test(file.type)) {
img = document.createElement("img");
img.setAttribute("class", "thumb");
img.setAttribute("id", "img_" + (indexN++));
reader.onload = (function(img, li) {
return function(evt) {
img.src = evt.target.result;
img.file = file;
};
}(img, li));
reader.readAsDataURL(file);
}
reader.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
progressBar.style.width = (evt.loaded / evt.total) * 100 + "%";
}
}, false);
reader.addEventListener("load", function() {
progressBarContainer.className += " uploaded";
progressBar.innerHTML = "";
}, false);
tBody = getTableBodyLayout(img, li);
document.getElementById("images_table").appendChild(tBody);
}
You can change addFilesToUpload() to take a callback when the file is done and change dropUpload() to initiate one at a time.
function dropUpload(event) {
noop(event);
var dropMethod = event.dataTransfer;
var classicMethod = event.target;
var dropedFiles = (dropMethod == undefined) ? classicMethod.files: dropMethod.files;
var filesDone = 0;
// local function to process the next file
function next() {
if (filesDone < dropedFiles.length) {
addFilesToUpload(dropedFiles[filesDone++], next);
}
}
// do the first one
next();
}
function addFilesToUpload(file, doneCallback) {
var li = document.createElement("li"), div = document.createElement("div"), img, progressBarContainer = document
.createElement("div"), progressBar = document.createElement("div"), tBody;
li.appendChild(div);
progressBarContainer.className = "progress-bar-container";
progressBar.className = "progress-bar";
progressBar.setAttribute("id", "proBar_" + (indexN++));
progressBarContainer.appendChild(progressBar);
li.appendChild(progressBarContainer);
var reader = new FileReader();
reader.onerror = function(event) {
alert("couldn't read file " + event.target.error.code);
};
// Present file info and append it to the list of files
fileInfo = "<div><strong>Name:</strong> " + file.name + "</div>";
fileInfo += "<div><strong>Size:</strong> " + parseInt(file.size / 1024, 10)
+ " kb</div>";
fileInfo += "<div><strong>Type:</strong> " + file.type + "</div>";
div.innerHTML = fileInfo;
if (reader !== "undefined" && (/image/i).test(file.type)) {
img = document.createElement("img");
img.setAttribute("class", "thumb");
img.setAttribute("id", "img_" + (indexN++));
reader.onload = (function(img, li) {
return function(evt) {
img.src = evt.target.result;
img.file = file;
// call the callback to tell the caller that this file is done now
doneCallback();
};
}(img, li));
reader.readAsDataURL(file);
}
reader.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
progressBar.style.width = (evt.loaded / evt.total) * 100 + "%";
}
}, false);
reader.addEventListener("load", function() {
progressBarContainer.className += " uploaded";
progressBar.innerHTML = "";
}, false);
tBody = getTableBodyLayout(img, li);
document.getElementById("images_table").appendChild(tBody);
}
If you want to wait to proceed to the next image until each image has loaded, then you could change the reader.onload handler to this:
reader.onload = (function(img, li) {
return function(evt) {
img.onload = function() {
// call the callback to tell the caller that this file is done now
doneCallback();
};
img.src = evt.target.result;
img.file = file;
};
}(img, li));