I have created a mobile application using ionic framework.It contains many images.I need to load all the images with out flickering.So i used $ImageCacheFactory for preloading all the images by refering this blog.
I used below code.The problem is that app contains 100 png images,So i have to refer all the png files.
.run(function($ImageCacheFactory) {
$ImageCacheFactory.Cache([
"img/user.png",
"img/profile.png",
"img/logo.png",
"img/splash.png",
"img/map.png",
"img/shop.png",
"img/country.png",
"img/place.png"
]).then(function(){
console.log("Images done loading!");
},function(failed){
console.log("Error..!!!");
});
})
Is there any easy method for refering all the png images with single line code(All the images are in www/img folder).Thanks
Create an angular factory as follows
.factory("$fileFactory", function($q) {
var File = function() {};
File.prototype = {
getEntries: function(path) {
var deferred = $q.defer();
window.resolveLocalFileSystemURI(path, function(fileSystem) {
var directoryReader = fileSystem.createReader();
directoryReader.readEntries(function(entries) {
deferred.resolve(entries);
}, function(error) {
deferred.reject(error);
});
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
};
return File;
});
Then to get list of all file using getEntries()
.run(function($ImageCacheFactory, $ionicPlatform, $fileFactory ) {
var fs = new $fileFactory();
$ionicPlatform.ready(function() {
fs.getEntries('img').then(function(result) {
var files = result;
files = files.unshift({
name: "[parent]"
}).map(function(i, v) {
return 'img/' + v.name;
});
$ImageCacheFactory.Cache(files).then(function() {
console.log("Images done loading!");
}, function(failed) {
console.log("Error..!!!");
});
})
});
});
You need to install dependencies Apache Cordova File
cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git
Reference : Helpful tutorial
Im sorry i dont have a n answer yet. But i know why it isnt working.
Using a Web Browser
Don't do it. If you even attempt to open this project in a web browser you're setting yourself up for failure. This application uses native device plugins that the web browser is unfamiliar with. In turn this will give strangeness and errors.
Related
I Am trying to make a web app load new pages without reloading in the browser. Some pages work fine while other raise errors since scripts are not loaded. The following code is the one to load a new page
function loadPage(target, savePushState){
$(".page-content").fadeOut(function(){
$('body').load(target, function(data) {
$(".page-content").fadeIn(function(){
var newTitle = $(data).filter('title').text();
document.title = newTitle;
if(savePushState){
var obj = { Title: newTitle, Url: target };
window.history.pushState(obj, obj.Title, obj.Url);
}
});
});
});
}
The page links with remote scripts specifically datatbles.net occasionally don't work.
Any tweaks to make it run smooth please.
The problem you've got is you haven't really thought about dependency management. You've got an elegant way of changing page, but no method to handle the requirements of those pages in terms of CSS/JS.
There's various tutorials and even frameworks that manage this sort of thing. One thing you could do is to declare each valid route's (i.e. page's) dependencies up front, and then load them when you call the route.
Since your loaded HTML seems to depend on JS before it can properly appear, we'll force the insertion of the HTML to wait for any and all JS dependencies to load.
const routes = {
'page1.html': {
js: ['https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js'],
css: ['https://guidecore.xyz/assets/css/main.css']
}
/* ... */
};
const pageContent = $('.page-content'); //<-- let's cache this element
function loadPage(target, savePushState) {
pageContent.fadeOut(function() {
//let's load dependencies
const promises = [];
['js', 'css'].forEach(type => {
routes[target] && (routes[target][type] ?? []).forEach(uri => {
if (type == 'js')
promises.push(fetch(uri)
.then(response => response.text())
.then(code => {
const el = document.createElement('script');
el.textContent = code;
document.body.appendChild(el);
})
);
else {
const el = document.createElement('link');
el.href = uri;
el.rel = 'stylesheet';
document.head.appendChild(el);
}
});
});
//wait for JS dependencies to load before we get new HTML
Promise.all(promises).then(() => {
$('body').load(target, function(data) {
pageContent.fadeIn(function(){
let newTitle = $(data).filter('title').text();
document.title = newTitle;
if(savePushState) {
var obj = { Title: newTitle, Url: target };
window.history.pushState(obj, obj.Title, obj.Url);
}
});
});
});
});
}
loadPage('page1.html');
I'm trying to output selected file's path in the DOM by using JS only.
For that I'm using
https://github.com/ihadeed/cordova-filechooser
&
https://github.com/hiddentao/cordova-plugin-filepath
plugins
openFile: function() {
fileChooser.open({ mime: "audio/mpeg" }, app.winCallback, app.failCallback); winCallback: function() {
let actualPath;
let err;
fileChooser.open(function(uri) {
window.FilePath.resolveNativePath(uri, actualPath, err);
alert(actualPath);
}); } , failCallback: function() {
console.log("Couldn't access files"); }
I'm getting the selected file's URI, But I'm unable to understand how to use this with cordova-plugin-filepath.
I'm trying to get a file path something like this
file:///storage/emulated/0/planetes.mp3
The function has to structured in following way. This seems to work on Android 6. The fileChooser plugin didn't work on android 4.4.2.
winCallback: function() {
fileChooser.open(function(uri) {
window.FilePath.resolveNativePath(uri, successNative, failNative);
function failNative(e) {
console.error("Something Went Wrong!");
}
function successNative(finalPath) {
var path = finalPath;
console.log(path);
document.getElementById("audio-file").src = path;
}
}); }
I m creating a hybrid app using Ionic. I created a folder in my DCIM folder of android where I save downloaded Images, Gifs.
Here is my code :
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
console.log("Root = " + fs.root.toURL() + "DCIM");
var entry=fs.root; entry.getDirectory("downloaded images", {create: true, exclusive: false},function (dirEntry) { },function (error) { }
);
}, function (error) {
});
});
Everything works fine. Only Problem is when I keep the foldername as "Downloaded_Images" or anything without space, I can see it in my android gallery , else the folder gets created but is not visible in gallery. But i need a folder with name "downloaded Images".
You could try something like this:
var yourDirectory = decodeURIComponent(fs.root + "downloaded%20images");
I have a post that work well when I run from VS2015 debug:
$("#DisplayChartType").bind("change", function () {
$.post("../Employee/ChangeDisplayChartType", { displayChartType: $("#DisplayChartType").val() }, function (data) {
iDependOnMyParameter(data);
})
});
But post does not work once I have published to IIS. I tried using ../, / and ~/ in the post but none work. I searched web and found the approach below but I still get ARG1 being sent as a parameter instead of my javascript variable.
$("#DisplayChartType").bind("change", function () {
$.post("#Html.Action("ChangeDisplayChartType", "Employee", new { displayChartType = "ARG1" })".replace("ARG1",$("#DisplayChartType").val()) , function (data) {
iDependOnMyParameter(data);
})
});
How should I do this? I really would like to stay with $.post approach as that works nicely in VS.
You can try this code.
$("#DisplayChartType").bind("change", function () {
var chartType = $("#DisplayChartType").val();
var url="#Url.Action("ChangeDisplayChartType", "Employee", new { displayChartType = "ARG1" })";
$.post(url.replace("ARG1", chartType), function (data) {
iDependOnMyParameter(data);
})
});
So add it to the url
$.post("../Employee/ChangeDisplayChartType?displayChartType=" + encodeURIComponent($("#DisplayChartType").val()), function(){});
or change your original code to GET and the value will be added to the querystring.
You can use window.location.origin or document.location.origin to get the origin of your website, whether running in VS 2015 debug or on IIS.
So instead of doing
$.post("../Employee/ChangeDisplayChartType"
You can try
$.post(document.location.origin + "/Employee/ChangeDisplayChartType"
#OJ Raqueno put me on the right path.
At top of script I now declare "myPath". My website URL ends with "secure" so this test gives me the right path:
var myPath = document.URL;
if (!myPath.endsWith("secure")) {
myPath = "";
}
Then I do this:
$("#DisplayChartType").bind("change", function () {
$.post(myPath + "/Employee/ChangeDisplayChartType", { displayChartType: $("#DisplayChartType").val() }, function (data) {
alert($("#DisplayChartType").val());
iDependOnMyParameter(data);
})
});
I am using PhantomJS to take a screenshot of a page every five minutes, and it works correctly most of the time. The problem is that sometimes the page I am taking a screenshot of fails to load the AngularJS library, and then, it can't build the page after that. So I am trying to figure out how to load a local copy in its place. Here is what I have been trying...
var page = require('webpage').create(),system = require('system');
var home = 'https://smartway.tn.gov/traffic/';
page.open(home, function (status) {
if(status === "success"){
page.injectJs('angular.js');
window.setTimeout((function() {
page.evaluate(function () {
/*stuff*/
});
}), 2000);
}
});
So angular.js is the name of my local copy of what the site would normally download. The site calls the script at the end of the body with several other scripts, and I am trying to find the best way to include it. I am wondering if it needs to be included by replacing the script tag in the html so it can be loaded in sequence, but I am not sure how to do that.
Thanks
It is problematic to reload a single JavaScript file when it failed, particularly when it is the framework. There are probably many scripts which depend on it. When the core framework is not loaded, those scripts will stop executing, because the angular reference cannot be resolved.
You could inject a local version of angular, but then you would have to go over all the other scripts which reference angular and "reload" them by either downloading and evaling them in order or putting them into the page as script elements. I advise against it, because it is probably very error prone.
You should just reload the page if angular does not exist after page load (callback of page.open). Since the same problem may occurr during reload, this has to be done recursively:
function open(countDown, done){
if (countDown === 0) {
done("ERROR: not loaded");
return;
}
page.open(home, function (status) {
if(status === "success"){
var angularExists = page.evaluate(function () {
return !!angular;
});
if (angularExists){
done();
} else {
open(countDown - 1, done);
}
} else {
open(countDown - 1, done);
}
});
}
open(5, function(err){
if(err) {
console.log(err);
} else {
page.render(target);
}
});
You can also try the page.reload() function instead of a page.open().
The other possiblity is to always inject the local version when the page loading began and stop any request for the remote version of the script:
page.onLoadStarted = function() {
page.injectJs('angular.js');
};
page.onResourceRequested = function(requestData, networkRequest) {
var match = requestData.url.match(/angular\.min\.js/g);
if (match != null) {
networkRequest.abort();
}
};
page.open(home, function (status) {
if(status === "success"){
window.setTimeout((function() {
page.evaluate(function () {
/*stuff*/
});
}), 2000);
}
});
This version works entirely without reloading.