How to remove caching with javascript code? - javascript

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});

Related

Javascript code isn't getting into my document ready listener. (forge iOS)

This is my entire javascript file for the home page of my app. Any ideas as to why it never gets into the document ready listener?
var photos;
forge.request.ajax({
url: "http://photos-url.com/pics.json",
dataType: "json",
success: function(data) {
photos = data;
},
error: function(error) {
forge.logging.info("Couldn't fetch pics!");
}
});
//logging output works here
$(function() {
//logging output doesn't work here
//I'm trying to append to the html here, but it never gets into this code
});
Cross-domain requests are prohibited for security reasons (same as in desktop browsers). You must configure environment to allow requests to your domain. Look at https://trigger.io/docs/current/api/modules/request.html for details.
json files are usually allowed to be read from cross domain and even if this one would't be, I still doubt it could affect ready event. I'm not using document ready function on my page as I was having simillar issues (it fires few minutes after page is loaded, or doesn't fire at all). You could try window.onload or document.onload events. I'd also try to find out how document.readyState behaves and eventually check it manually with interval or try to bind event listener to it.

Dealing with pages with many script files

Our project contains many pages which has up to 20 tabs, each works with different scripts. All the script files are referenced in <head> and loads on the first page load. Now we have performance issue because there are too many scripts on the page loads on opening it (about 2k lines of JavaScript per tab). The matter is in much cases user needs to work with 2-3 tabs and as a result more than 60% of code becomes not used. So we need any scripts lazy-loading solution to ease the pages. As HTML for every tab is loaded on demand we can put <script> references in every tab that will provide a good working solution. But I'm prety sure including references not in <head> is a bad style.
So I wonder, is there any another solution? How such problems are solved in big projects like us? Any advice will be helpfull.
Thanks in advance!
jQuery has a great function for this sollution:
$.getScript("my_lovely_script.js", function(){
alert("Script loaded and executed.");
// here you can use anything you defined in the loaded script
});
This is by default not cached. I looked for a solution on the jQuery website it stated this solution for a cached script include.
jQuery.cachedScript = function(url, options) {
// allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "script", //Note this
cache: true, //Enable caching
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
// Usage
$.cachedScript("URL HERE").done(function(script, textStatus) {
console.log( textStatus );
});

Problem with IE and setInterval() not refreshing/updating

I'm using JavaScript/Jquery to make a page auto-update with a value from a database, although it doesn't seem to update in Internet Explorer. It works fine in FireFox & Chrome. Can anyone explain what's wrong? It looks like IE is just displaying a cached version of the page. How can I prevent this happening? Thanks.
function updateComm() {
var url="commandSys.php";
jQuery("#theElement").load(url);
}
setInterval("updateComm()", 1000);
Try disabling the cache with ajaxSetup
$.ajaxSetup ({
// Disable caching of AJAX responses */
cache: false
});
function updateComm() {
var url="commandSys.php";
jQuery("#theElement").load(url);
}
setInterval(updateComm, 1000);
Alternatively, you can manually just append a +new Date to url so it appends a query string to prevent caching.
Alternatively, disable caching on the server-side.
Your php page is cached. Has nothing to do with the interval. Set the right caching headers on the page.

Any way to gracefully enforce a timeout limit when loading a slow external file via javascript?

I'm using javascript to include some content served up from a php file on another server. However, this other service can sometimes get flaky and either take a long time to load or will not load at all.
Is there a way in JS to try to get the external data for x number of seconds before failing and displaying a "please try again" message?
<script type="text/javascript" src="htp://otherserver.com/myscript.php"></script>
Couple issues: you can use timeout thresholds with XMLHttpRequest (aka ajax), but then since it's on an otherserver.com you cannot use XMLHttpRequest (and support all A-grade browsers) due to the Same Origin Policy restriction.
If the script introduces any kind of global name (eg any variable name, function name, etc) You can try setTimeout to keep checking for it:
var TIMELIMIT = 5; // seconds until timeout
var start = new Date;
setTimeout(function() {
// check for something introduced by your external script.
// A variable, namespace or function name here is adequate:
var scriptIncluded = 'otherServerVariable' in window;
if(!scriptIncluded) {
if ((new Date - start) / 1000 >= TIMELIMIT) {
// timed out
alert("Please try again")
}
else {
// keep waiting...
setTimeout(arguments.callee, 100)
}
}
}, 100)
The problem as I see it is you cannot cancel the request for the script. Please someone correct me if I'm wrong but removing the <script> from the DOM will still leave the browser's request for the resource active. So although you can detect that the script is taking longer than x seconds to load, you can't cancel the request.
I think you may be out of luck.
The only way I can think of doing this is to create a proxy on another (PHP-enabled) server which will fetch the data for you, but will stop when a certain timeout limit has been reached (and it can just return an empty result).
This is purely, purely theoretical:
<script> tags can be dynamically inserted into the DOM, at which point the script will be fetched and processed. This dynamic script tag injection is how some achieve cross-domain "AJAX."
I would imagine you could declare a global variable var hasLoaded = false;. At the end of the script you are attempting to load you could set that variable to true hadLoaded=true;. After injecting the script tag into the DOM you could then kickoff a setTimeout() whose callback function checks to see if "hasLoaded" is set to true. If it isn't, you can assume the script has not yet loaded fully into the browser. If it has, you can assume it has loaded completely.
Again, this is theoretical, but if you test it be sure to report back, I'm very curious.
I think that the only way to do this is take the content of the file via ajax and then set a timer. If the request finishes before the timer you can evaluate the respons with eval(that's not the better solution anyway), otherwise you can stop the ajax request and write the error message.

Making DiveIntoPython3 work in IE8 (fixing a Javascript performance issue)

I am trying to fix the performance problem with Dive Into Python 3 on IE8. Visit this page in IE8 and, after a few moments, you will see the following popup:
alt text http://dl.getdropbox.com/u/87045/permalinks/dip3-ie8-perf.png
I traced down the culprit down to this line in j/dip3.js
... find("tr:nth-child(" + (i+1) + ") td:nth-child(2)");
If I disable it (and return from the function immediately), the "Stop executing this script?" dialog does not appear as the page now loads fairly fast.
I am no Javascript/jquery expert, so I ask you fellow developers as to why this query is making IE slow. Is there a fix for it?
Edit: you can download the entire webpage (980K) for local viewing/editing.
This seems to need a bit of rewriting.
nth-child is a slow operation. You should implement the current functionality by generating classes or ids that would be common for the TDs in table and elements from the refs collection (dip3.js line 183). and then:
refs.each(function(i) {
var a = $(this);
var li = a.parents("pre").next("table").find("td."+a.attr('class'));
li.add(a).hover(function() { a.css(hip); li.css(hip); },
function() { a.css(unhip); li.css(unhip); });
});
This popup message is misleading - it doesn't actually mean that IE is running slowly, but that the number of executed script statements has exceeded a certain threshold. Even if the script executes very quickly, you'll still see this message if you go over the limit. The only way to get rid of it is to reduce the number of statements executed or edit the registry.
http://support.microsoft.com/kb/175500
I find Microsoft's implementation of this very annoying. It makes assumptions about the speed of your computer.

Categories

Resources