Javascript in Safari not always running - javascript

Am having an issue with Safari. I have a basic script using jQuery that makes some changes to a form field and adds some behaviours to it. When I run this script on using the document ready method it's fine in Firefox but in Safari it doesn't always run the initial changes. I can hit refresh and get it running fine 4/5 times, but sometimes it just doesn't initialise like it should.
This is running on a local server so the refresh is pretty quick, I'm wondering if the javascript is executing before the page has finished loading. I've tried calling the script in the foot of the page rather then the header but that hasn't helped. I remember hearing about different browsers firing document ready at different times and thought this would help remedy it but it hasn't and I can't find any further information on that topic.
Anything I'm missing that could be the issue or a workaround? The script itself doesn't seem to be at fault. Am using the jQuery colours plugin, apart from that it's only jQuery and my script.
Help is always appreciated, thanks people!
Here is the code. initSearchBox() is run using the line below in the header.
$(document).ready(function() { initSearchBox() ; });
function randomFieldValue(){
var options = new Array(
'Lorem',
'Ipsum',
'Dolor',
'Sit',
'Amet'
)
t = Math.floor(Math.random()*(options.length - 1));
return options[t] ;
}
function initSearchBox(){
instanceDefText = randomFieldValue() ;
$('#search-form-field')
.attr('value',instanceDefText)
.css('color','#fff')
.animate({color:'#999'},1500)
.focus(function(){
if($(this).attr('value') == instanceDefText){
$(this).attr('value','')
.css('color','#000')
}
})
.blur(function(){
if($(this).attr('value') == ''){
instanceDefText = randomFieldValue() ;
$(this).attr('value',instanceDefText)
.css('color','#fff')
.animate({color:'#999'},1500)
}
});
}

Related

Why this polling stops working after idling for some time?

I am using AngularJS to constantly poll for new data through HTTP POST. An alert will be sent when new data is received. The code which is inside a controller looks something like this;
var poll = function() {
$http.get('phones.json').success(
function(data)
{
new_val = data.val;
if ( (new_val!== old_val) )
{
$window.alert("AlertEvent");
}
old_data = new_val;
$timeout(poll, 500);
}
);
};
poll();
This code works when the html page is refreshed. Working means when phones.json is changed, an alert will appear. However, if I leave the page on for, say 30 minutes, and come back later, it stops working. I have to refresh the page to get it working again.
What else did I miss out? What did I do wrong? Could it due to some caching mechanism?
Thank you very much.
EDIT: I found the cause. It is indeed due to the browser reading from cache. I can see this using Chrome Developer tools. How can this caching be disabled for this html page only?
You may be able to bust the cache by doing something like this:
$http.get('phones.json?v=' + Date.now())
Depending on how your back-end is set-up you may need to adjust it to accept that.

Reload updated java<script> code without fully reloading the html page

I am developing a single page web application, that has many different features and forms. When developing a deep (I mean something that is not on the home page) feature, I go through this cycle:
develop the code, editing classes and functions
refresh the whole page
clicking all the way till I get to the part that I need to test (that adds up to about a minute sometimes)
testing the new code
back to the (1) code editor doing updates
doing about 15 minor edits, can take a frustrating 30 minutes of repeated reloading and clicking
Is there any plugin, piece of javascript, or method, that allows to reload the updated javascript without reloading everything, so one can skip the 2. and 3. from the cycle above and continue doing live tests?
If there's no such thing, I am planning on developing a little javascript plugin that will reload the scripts, and probably with socket.io connection to a backend node.js server that will watch the files for any updates and push the load events to the browser.
So, I am interested in any idea about this, any thing that I should take into consideration when writing the plugin.
Thanks : )
You could do something like this.
function LoadMyJs(scriptName) {
var docHeadObj = document.getElementsByTagName("head")[0];
var dynamicScript = document.createElement("script");
dynamicScript.type = "text/javascript";
dynamicScript.src = scriptName;
docHeadObj.appendChild(newScript);
}
Call the LoadMyJs function on page load
<body onLoad="LoadMyJs()">
Then reload with the click of a button (or from your console)
<input type="button" name="reloadjs" value="Reload JavaScript" onclick="LoadMyJs('my_live_loading_script.js')">
This could be simplified using e.g jQuery
Thanks to:
http://www.philnicholas.com/2009/05/11/reloading-your-javascript-without-reloading-your-page/
Here's what I came up with: a Node.js module that watches for changes in .js & .coffee scripts, and pushes the changes to the browser upon editing the files.
It works standalone, even if you are developing on filesystem file:/// without using a web server.
It works with any framework, just launch the standalone script and point it to your js/ directory.
It has an express.js helper, that make it run using the same server instance.
It is as easy as
adding a single line of <script> tag to your existing code, and
running the live script, pointing it to the html root.
code: 🐱/etabits/live.js
That's may be not the best answer but for local developments I use that firefox plugins:
https://addons.mozilla.org/en-US/firefox/addon/auto-reload/
This reload the css, js or anything present in a directory
For dev which really needs to be remotely , I use that small js code you can adapt for reloading js.
function refreshCss(rule){
if (rule == null)
rule = /.*/;
var links = document.getElementsByTagName("link");
for(var i=0;i<links.length;i++)
{
if (!links[i].href.match(rule))
continue;
if (! links[i].href.match(/(.*)time=/)){
if (links[i].href.match(/\?/))
var glue = '&';
else
var glue = '?';
links[i].href += glue+"time="+new Date().getTime();
}
else{
links[i].href.replace(/time=\d+/, "time"+new Date().getTime());
}
}
if (!no_refresh)
{
setTimeout(function(){refreshCss(rule)}, 5000);
}
};
// and then call it refreshCss("regex to match your css, or not"); var no_refresh=false;
Edit: this is a version with "setTimeout", but you can easily made a "keypress" version of it
Replace with dynamic script.
function LoadMyJs(scriptName)
{
var docHeadObj = document.getElementsByTagName("head")[0];
var dynamicScript = document.createElement("script");
dynamicScript.type = "text/javascript";
dynamicScript.src = scriptName;
docHeadObj.appendChild(dynamicScript);
}

Redirect Plugin Not working

I'm trying to create a Redirect timer plugin from all JS (JQuery) but for some reason its not updating the timer since I started using a different method:
(function( $ ){
$.fn.redirect = function( options ) {
var settings = {
'second' : '10'
};
var options=$.extend( settings, options );
return this.each(function() {
var o=options;
if(o.second!==false){
var Seconds = o.second;
} }); };
})( jQuery );
Note this is not the whole code but you can check out the whole code here:
http://jsfiddle.net/NVx8w/6/
The reason I didnt just post the code here is because I think that JS Fiddle is easier to edit with. Some people complain that I only give a link but note: "When you click the link it WILL give you a code in an edit"
At the moment it is messy and hard to read, but once I get the seconds to work correctly I can set everything up like its suppose to.(:
Any suggestion would be helpful.
Your problem is that you have a variable Second in this statement:
setTimeout("$('#re_message').hide();$('#redirect1').delay(50).fadeIn();", Second + 500);
when it should be Seconds. If you fix that the script will work. I recommend using Firebug (in Firefox) or Web Inspector in Safari/Chrome, the console in both those tools could've pointed you towards that issue within seconds. ;)

IE stop script warning

Only in IE I get a warning when loading my site containing javascript saying that its causing the page to run slowly (and asking if I want to stop it).
I've seen other posts about this and I've looked for any long running code or infinite loops etc. The weird thing is, when I select 'No' (to not terminate the script) the page immediately loads properly. Its almost like this warning comes up right before the page is done loading. Has anybody experienced this, or know why this might be happening?
IE has its own way of making your life impossible.
Just deactivate the warning, you can further research in the future if that's necessary.
This article might help you determine why IE is giving such a warning.
Regards,
Adapted from http://www.codeproject.com/Tips/406739/Preventing-Stop-running-this-script-in-Browsers
// Magic IE<9 workaround for irritating "Stop running this script?" dialog.
RepeatOperation = function(anonymousOperation, whenToYield){
var count = 0
return function(){
if (++count >= whenToYield){
count = 0
setTimeout(function(){anonymousOperation()}, 100)
}
else anonymousOperation()
}
}
// How to implement the workaround:
//for (var i in retailers){ // Too big for IE<9! Use magic workaround:
var i = 0; var noInArray = retailers.length
var ro = new RepeatOperation(function(){
// <<Your loop body here, using return instead of continue.>>
if (++i < noInArray) ro()
else alert("Loop finished.")
}, 200) // Run this in batches of n. 500 is too much for IE<9.
ro()

Help making userscript work in chrome

I've written a userscript for Gmail : Pimp.my.Gmail & i'd like it to be compatible with Google Chrome too.
Now i have tried a couple of things, to the best of my Javascript knowledge (which is very weak) & have been successful up-to a certain extent, though im not sure if it's the right way.
Here's what i tried, to make it work in Chrome:
The very first thing i found is that contentWindow.document doesn't work in chrome, so i tried contentDocument, which works.
BUT i noticed one thing, checking the console messages in Firefox and Chrome, i saw that the script gets executed multiple times in Firefox whereas in Chrome it just executes once!
So i had to abandon the window.addEventListener('load', init, false); line and replace it with window.setTimeout(init, 5000); and i'm not sure if this is a good idea.
The other thing i tried is keeping the window.addEventListener('load', init, false); line and using window.setTimeout(init, 1000); inside init() in case the canvasframe is not found.
So please do lemme know what would be the best way to make this script cross-browser compatible.
Oh and im all ears for making this script better/efficient code wise (which im sure is possible)
edit: no help...? :'(
edit 28-Apr:
i re-wrote the code a little and now it looks something like this.:
if(document.location != top.location) return;
(function() {
var interval = window.setInterval(waitforiframe, 3000);
var canvas;
function waitforiframe() {
console.log("Finding canvas frame");
canvas = document.getElementById("canvas_frame");
if (canvas && canvas.contentDocument) {
console.log("Found canvas frame");
pimpmygmail();
}
}
function pimpmygmail() {
gmail = canvas.contentDocument;
if(!gmail) return;
window.clearInterval(interval);
console.log("Lets PIMP.MY.GMAIL!!!");
......rest of the code......
})();
This works perfectly fine in Firefox, but in Chrome, it gives me a top is undefined error.
Another thing i noticed is that if i remove the first line if(document.location != top.location) return; , the waitforiframe() method keeps getting called over and over again. (ie i see the "Finding canvas frame" error in the console)
can someone tell me what does the first line do? i mean what does it achieve & why does the waitforiframe() method run forever if i remove that line??
A BIG THANK YOU TO ALL WHO HELPED! -_- meh
btw, this was all i needed at the beginning of the script:
try { if(top.location.href != window.location.href) { return; } }
catch(e) { return; }

Categories

Resources