I am using the following JavaScript code and I am trying to find out once the file has been downloaded and added to the header of my page:
function loadjscssfile(filename, filetype)
{
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadjscssfile("jquery.js","js");
I normally use the following code to find out once my image has loaded:
document.getElementById("header_logo").src = "logo.png"; // load top logo
var header_logo = document.getElementById("header_logo");
header_logo.onload = function(e) {
// do something here, the file has loaded
}
but I can't work out how to check once my JS has been loaded..
Any ideas?
(I can't use jQuery.)
You could add a function to the onload event:
function loadjscssfile(filename, filetype, onload) {
//if filename is a external JavaScript file
if (filetype == "js") {
var fileref = document.createElement('script');
fileref.type = "text/javascript");
fileref.onload = onload;
fileref.src = filename);
document.getElementsByTagName("head")[0].appendChild(fileref);
return;
}
//if filename is an external CSS file
if (filetype == "css") {
var fileref = document.createElement("link");
fileref.rel = "stylesheet";
fileref.type = "text/css";
fileref.onload = onload;
fileref.href = filename;
document.getElementsByTagName("head")[0].appendChild(fileref);
return;
}
}
loadjscssfile("jquery.js","js", function() { alert(this.src); });
In HTML 4.01 the load event was onlly supported by body and frameset elements, though many support it for img elements and some for script elements.
In HTML5, script elements have beforescriptexecute, afterscriptexecute and load events that are dispatched at relevant times in the script element's life. However, support for those events is likely not available in many browsers in use so not to be relied upon.
The most robust way to see if a script has loaded is to test for a value of a variable that is assigned a value by the last bit of code to be executed, e.g. final statements like:
var loadedScripts = loadedScripts || {};
loadedScripts.fooScript = true;
Then you can test for it:
if (loadedScripts.fooScript) {
// loaded
} else {
// not loaded
}
Related
Downloaded the file in Safari the file name is "Unknown"
Here is my download code
function downloadCSV(csv, filename) {
var downloadContainer = angular.element(''),
content = 'data:attachment/csv,' + encodeURI(csv);
// var downloadLink = angular.element('<a></a>'),
var downloadLink = angular.element(downloadContainer.children()[0]),
blob = new Blob([csv], {
type: 'text/csv;charset=utf-8;'
});
if (window.navigator.msSaveOrOpenBlob) {
// download file for IE
navigator.msSaveBlob(blob, filename);
}
else {
downloadLink.attr('href', content);
downloadLink.attr('download', filename);
downloadLink.attr('style', 'display: none');
// workaround for Safari version that not supporting download feature.
downloadLink.attr('target', '_blank');
angular.element(document).find('body').append(downloadContainer);
// need timeout here since appending DOM takes some time
$timeout(function() {
downloadLink[0].click();
downloadLink.remove();
}, 10);
}
}
and call this function with
downloadCSV(cvs, 'myDownloadFile.csv')
But the downloading the file using Safari is "Unknown" file. Is there any workaround this issue.
BTW - what version of Safari does not support download feature.
Thanks
Safari version < 9.X didn't support download the file.
Code to download the file
function downloadCSV(csv, filename) {
var downloadContainer = angular.element('<div data-tap-disabled="true"><a></a></div>');
// var downloadLink = angular.element('<a></a>'),
var downloadLink = angular.element(downloadContainer.children()[0]),
blob = new Blob([csv], {
type: 'text/csv;charset=utf-8;'
});
if (window.navigator.msSaveOrOpenBlob) {
// download file for IE
navigator.msSaveBlob(blob, filename);
}
else {
downloadLink.attr('href', window.URL.createObjectURL(blob));
downloadLink.attr('download', filename);
downloadLink.attr('style', 'display: none');
angular.element(document).find('body').append(downloadContainer);
// need timeout here since appending DOM takes some time
$timeout(function() {
downloadLink[0].click();
downloadLink.remove();
}, 10);
}
}
Our application to allow the admin to download the file and it works for all browser but not Safari 9.1.2(11601.7.7).Is there any workaround to make in download attribute to make download feature works for Safari?
Thanks
Kim
I can download a PDF using AngularJS in Chrome, but this doesn't appear to work in the latest FireFox, Internet Explorer 11 or Edge (assuming it doesn't work for IE10 either), and I know a shim is needed for IE9. Don't know if this the best shim for this if anyone has an opinion, but currently it doesn't seem to work. I tried it with a response type of blob and arraybuffer just in case that made a difference, and it doesn't.
All this counters what caniuse indicates about using the Blob URLs. Anyone have this working in IE9 and up, and the last couple versions of FF, and can point out what I'm doing wrong?
$http({
url: '/api/v1/download',
method: 'GET',
responseType: 'blob' // or 'arraybuffer'
}).then(function (response) {
// Use the Blob object to create an object URL to download the file
var url = URL.createObjectURL(response.data);
// var url = URL.createObjectURL(new Blob([response], {type: 'application/pdf'})); // arraybuffer version
// Create an anchor to perform download, but don't append to the DOM
anchor.href = downloadUrl;
anchor.download = filename;
anchor.target = '_blank';
anchor.click();
URL.revokeObjectURL(downloadUrl);
anchor = null;
}).catch(function (reason) {
console.log('FAIL', reason);
});
UPDATE
Currently the best (only) answer works for IE10, 11, Edge, FF, and continues to work with Chrome. IE9 won't work using this solution if anyone has another polyfill/shim/other/etc, and Safari doesn't support the download attribute so the solution in the chosen answer doesn't work in an SPA since it just redirects the current page so in both these cases I've just left TODO stubs.
This is an update to the posted answer with more information added in comments for anyone to use or hopefully add to so IE9 and Safari work as expected:
function performDownload(blob, filename) {
// IE9 has no API for handling downloads using Blob objects, and doesn't support the download attribute
if(isIE() == 9) {
// TODO: polyfill/shim/other... change response type to?
}
// Only works for IE10 and up, including Edge
else if (typeof window.navigator.msSaveBlob !== 'undefined') {
// Provides a prompt to save the file to a location of users choice
window.navigator.msSaveBlob(blob, filename);
}
// Browsers that adhere to current standards can implement downloads
// using the Blob object with the download anchor attribute
// ---
// NOTE: Edge 13+ is compliant with both these standards, but Edge 12
// does not support the download anchor attribute so all versions
// have been grouped to use the propriety `msSaveBlob` method
else {
// Use the Blob object to create an object URL to download the file
var URL = window.URL;
var downloadUrl = URL.createObjectURL(blob);
var anchor = document.createElement('a');
if(angular.isDefined(anchor.download)) {
anchor.href = downloadUrl;
anchor.download = filename;
anchor.target = '_blank';
document.body.appendChild(anchor); // Required by Firefox
anchor.click();
// Release the existing object URL, and the anchor
$timeout(function () {
URL.revokeObjectURL(downloadUrl);
document.body.removeChild(anchor);
anchor = null;
}, 100);
}
else {
// TODO: Safari does not support the download anchor attribute...
}
}
}
I've used this with success in both IE11 and Chrome:
function saveBlob(response, contentType, filename) {
let blob = new Blob([response.arrayBuffer()], { type: contentType });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround
window.navigator.msSaveBlob(blob, filename);
} else {
let URL = window.URL;
let downloadUrl = URL.createObjectURL(blob);
if (filename) {
let a = document.createElement('a');
if (typeof a.download === 'undefined') {
window.location.href = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location.href = downloadUrl;
}
// cleanup
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100);
}
}
I have a JavaScript problem.
I searched on google how to append using javascript and I found an example. I want to manually append a script tag to head or body, but the example just appends in the head.
I edited the example so that the script tag can be appended in the head or body, but the code doesn't work.
Can anyone help me fix my problem? And please show me the demo on jsfiddle :D
Thanks :)
Here my script:
//JS
//Defined with loadjscssfile("yourcssurl.js", "js", "head"); or addCss("yourcssurl.js", "js", "body");
//CSS
//Defined with loadjscssfile("yourcssurl.css", "css", "head"); or addCss("yourcssurl.css", "css", "body");
function loadjscssfile(filename, filetype, pos) {
if (filetype == "js") { //if filename is a external JavaScript file
var fileref = document.createElement('script')
fileref.setAttribute("type", "text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype == "css") { //if filename is an external CSS file
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref == filetype) {
document.getElementsByTagName(pos)[0].appendChild(fileref)
}
else if (typeof fileref != "undefined") {
document.getElementsByTagName("head")[0].appendChild(fileref)
}
}
loadjscssfile("myscript.js", "js", "body") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js", "body") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css", "body") ////dynamically load and add this .css file
And here is the original script, before I edited: Dynamically loading an external JavaScript or CSS file
Sorry for my bad english :)
You can learn from google to appending scripts dynamically
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
I'm not sure what you are trying to achieve at the end of the day, but take a good look at the script, it's async. So you do not worry about the sequence of the resource loading.
In some use cases, you might need to control the sequence of the script loading, you can consider using RequireJS or Modernizr
You are pretty close, but you don't need the extra if condition you added, this should be sufficient:
function loadjscssfile(filename, filetype, pos) {
var fileref;
if (filetype === "js") { //if filename is a external JavaScript file
fileref = document.createElement("script");
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", filename);
}
else if (filetype === "css") { //if filename is an external CSS file
fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
}
if (fileref) {
document.getElementsByTagName(pos)[0].appendChild(fileref);
}
}
Give that a shot.
When I load a sound file with Javascript, the file seems to load from remote server each time. Is it possible to cache the file once loaded? I would like to load once and play as required.
var soundEmbed = null;
function playSound()
{
var myWAVfile = "myfile.wav";
if (soundEmbed)
{
document.body.removeChild(soundEmbed);
}
soundEmbed = document.createElement("embed");
soundEmbed.setAttribute("src", myWAVfile);
soundEmbed.setAttribute("hidden", true);
soundEmbed.setAttribute("autostart", true);
document.body.appendChild(soundEmbed);
}