Save plugin loaded with Ajax to cache - javascript

So I'm using this code to change the content of my website and loading specific plugins for each "page":
$.ajax({
url: urlPath,
type: 'GET',
success: loadContent //content and plugins are loaded through this
});
Now I noticed it doesn't cache the loaded plugins from loadContent, each time downloading them again and again, thefore the page using ajax requests is 0.5s to 1.5s slower than simple http requests (obviously after the plugins have already been cached from first load).
Using cache: true/false doesn't make any difference.
I've read this can't be done, because javascript can't write to disk, but still maybe I missed something and there is a way to cache the plugins and avoid losing additional time on each load?

You can use an alternative to cache which is localStorage. Each website has the right to store up to 5 MB of data on the user disk.
So use this to save data:
//browser support localStorage
if((typeof(Storage) !== "undefined"){
localStorage.setItem("mydataname", data);
}
And to retrieve or download a new one:
//browser support localStorage
if((typeof(Storage) !== "undefined"){
var data = localStorage.getItem("mydataname");
if(data){ //data does exist in localStorage
// Use data, no need to download a new version.
}
else{ // data doesn't exist, not saved yet or have been removed
// download new version of data and save it using the above code.
}
}
else{
// browser doesn't support localStorage redownload data.
}
More about localStorage here.

Related

jQuery check if a file exist locally

I am developing a local site for a company (only local internal use, offline and without server). I have a main page that has a main div, that contain 3 different div. Each div is linked to a page and the "onclick" event of each div will load the page linked into the main div. So i have to check, with the document ready function, if each page exists and, if not, I want to delete the div linked to that page. How can I check if a page exist locally? I've found many answere that check with status of connection if a page exists, but my html will only work offline and locally, so I can't use that method.
EDIT - SOLVED
I've solved this using the script of #che-azeh:
function checkIfFileLoaded(fileName) {
$.get(fileName, function(data, textStatus) {
if (textStatus == "success") {
// execute a success code
console.log("file loaded!");
}
});
}
If the file was successfully load, i'd change the content of a new hidden div that will tell to another script if it have to remove or not each of the three div.
This function checks if a file can load successfully. You can use it to try loading your local files:
function checkIfFileLoaded(fileName) {
$.get(fileName, function(data, textStatus) {
if (textStatus == "success") {
// execute a success code
console.log("file loaded!");
}
});
}
checkIfFileLoaded("test.html");
I suggest you run a local web server on the client's computer. (See also edit below on local XHR access).
With a local web server they can start it up as if it was an application. You could for example use node's http-server. You could even install it as an node/npm package, which makes deployment also easier.
By using a proper http server (locally in your case) you can use xhr requests:
$(function(){
$.ajax({
type: "HEAD",
async: true,
url: "http://localhost:7171/myapp/somefile.html"
}).done(function(){
console.log("found");
}).fail(function () {
console.log("not found");
})
})
EDIT:
Firefox
Another post has (#che-azeh) has brought to my attention that firefox does allow XHR on the file "protocol". At the time of this writing the above works in firefox using a url of just somefile.html and using the file scheme.
Chrome
Chrome has an option allow-file-access-from-files (http://www.chrome-allow-file-access-from-file.com/). This also allows local XHR request
This flag is intended for testing purposes:
you should be able to run your tests in Google Chrome with no hassles
I would still suggest the local web server as this make you independent of these browser flags plus protect you from regression once firefox/chrome decide to disable support for this.
You can attempt to load the page within a try-catch construct. If the page exists, it will be loaded though. If it doesn't, you can (within the catch) set the related div as hidden.
Try to access the page using $.ajax. Use the error: option to run a callback function that removes the DIV linked to the page.
$.ajax({
url: "page1.html",
error: function() {
$("#page1_div").remove();
});
You can loop this code over all the DIVs.
You can use jquery load function
$("div").load("/test.html", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$(this).html(msg + xhr.status + " " + xhr.statusText);
}
});

Is there another way to disable cache when fetching script?

I use this to fetch script;
$.getScript("http://www.example.org/");
However, I dont want it to be cached. Means that if I use getScript again, the script should fetch it again.
This one works in theory;
$.getScript("http://www.example.org/?" + Math.random());
But in practically, it's not. Because the "?" is disabled on the remote site url, so my question is, is there any otherway to tell browser to not cache ?
Recreate the function for your needs:
(function () {
$.getScript = function(url, callback) {
$.ajax({
type: "GET",
url: url,
success: callback,
dataType: "script",
cache: false
});
};
})();
Now it won't cache anymore when you call the function like
$.getScript('script.js', function()
{
// non cached script.js
});
The remote site cannot disable the effectiveness of "http://www.example.org/?" + Math.random() to prevent caching.
The point of the "?" + Math.random() is to create a unique URL that will not be in the local browser cache. It is the local browser that makes this caching decision and, for local browser caching, it does not matter if the remote site is ignoring the "?" + Math.random() part of the URL or not.
FYI, another way to address caching is for your server to return proper cache headers when this script is retrieved that instruct the browser to never cache this file.

Preloading images with AJAX for AJAX

My site structure is sequential (as in page1.html leads to page2.html, page2.html leads to page3.html, etc.). I'm wanting to preload some images from the third page on the second page. I've found this wonderful bit of code here on SO:
$.ajax({
url : 'somePage.html',
dataType : "html",
success : function(data) {
$(data).hide().appendTo('#someDiv');
var imagesCount = $('#someDiv').find('img').length;
var imagesLoaded = 0;
$('#someDiv').find('img').load( function() {
++imagesLoaded;
if (imagesLoaded >= imagesCount) {
$('#someDiv').children().show();
}
});
var timeout = setTimeout(function() {
$('#someDiv').children().show();
}, 5000);
}
});
It works beautifully at dumping the entire contents of page3.html onto page2.html. The problem is, I don't want the entire contents; I just want the images, and I want them hidden and ready for when the user actually loads page3.html. The above snippet brings audio and, well, everything else along with it. So my question is, will this hacked up version below work for my purposes?
$.ajax({
url : 'page3.html',
dataType : "html",
success : function(data) {
var imagesCount = $(data).find('img').length;
var imagesLoaded = 0;
$(data).find('img').load( function() {
++imagesLoaded;
if (imagesLoaded >= imagesCount) {
//halt? do something?
}
});
}
});
Again, all I want is for page3.html's images to be preloaded on page2.html. Will this do the trick? And how can I test to verify?
I believe the simplest way, in your case, is just to use jQuery.get and specify the images (or any other objects) you want to preload.
For example,
$.get('images/image1.jpg');
$.get('images/image2.jpg');
// etc
This way, you can specify which images from the next page you want to preload in the browser.
The $.get function is just an abbreviated version of the $.ajax function. In your case, you just want to "get" the images so that they are in the browser's cache, so that when you get to the next html page, the images are already loaded.
How to verify
If you were to add the sample code above to your page2, then visit that page while having the Network tab open in Firebug, or Chrome dev tools, you'll see that GET requests are sent for the images and they are loaded to the browser's cache.

Inline cache <script> of ajax content

I need to cache some <script src> that I receive via AJAX. Currently each call try to load the src via AJAX, as default. But the problem is that this script never change in a session and I need only re-eval this on document.
To be more clear, take this example of AJAX content result:
<strong>Hello World!</strong>
<script src="hello-world.js"></script>
If I call this AJAX three times, the hello-world.js is called three times too, but I need only re-execute this, without try to download it again. Browser cache help a lot, but I really do not can download it again every time.
I like to set some data to script, to jQuery know that I want only re-execute it, instead of download again. Like:
<script src="hello-world.js" data-cache="true"></script>
Any solution?
If think about a good solution for my case... I just replaced the src with data-src, so jQuery will not get the content automatically, so I have time to work with my content and find data-src and create my own cache system. Works fine to me.
You can check my code here:
// Cache system (outside of AJAX engine)
var script_cache = {};
// Inside of [jQuery.ajax].success method
// where "data_html" is my jQuery(data_html) AJAX response.
// Find all script with data-src
jQuery('script[data-src]', data_html).each(function() {
var self = jQuery(this),
self_src = self.data('src');
// If data was loaded before, so just execute it again
if(typeof script_cache[self_src] !== "undefined") {
jQuery.globalEval(script_cache[self_src]);
}
// Else, will load, cache and execute now
// Note that we download with dataType text
else {
jQuery.ajax(self_src, {
dataType: "text"
}).success(function(data) {
script_cache[self_src] = data;
jQuery.globalEval(data);
});
}
// Finally we remove the node, only to avoid problem
self.remove();
});
Alternative solutions are welcome.

How to remove caching with javascript code?

I have small problem with my recent project build in HTML and Javascript + jQuery only. I would like to prevent page caching as I need to refresh some area of page with some time interval.
If I reload the page, then we can set the "no-cache" META tag into header. But I am not going to reload the page and though jQuery calls XML files with AJAX those javascript files are getting cached and Memory overhead occurs. Because of this my FireFox crashes and memory usages increase up to 2 GB.
Can any one suggest me something fruitful so that I can solve memory overhead problem and running my application over browser smoothly.
function refresh() {
$('#table_info').remove();
$('#table').hide();
if (refreshTimer) {
clearTimeout(refreshTimer);
refreshTimer = null ;
}
$.ajax({
document.getElementById('refresh_topology').disabled=true;
$('<div id="preload_xml"></div>').html('<img src="pic/dataload.gif" alt="loading data" /><h3>Loading Data...</h3>').prependTo($("#td_123"));
$("#topo").hide();
$('#root').remove();
show_topology();
});
}
This is the code and show_topology() is been called frequently to make different status of Topology everytime.
disable jquery ajax cache:
$.ajax({cache: false});

Categories

Resources