Is there an easy/efficient way to detect if an img element load has started and/or a request has been made to the server?
I swear I remember seeing (the first part of) this before on SO, but can't find it now.
I think I remember that the naturalWidth and naturalHeight properties are present if the image has started loading, but IDK if that is always true.
I am working with lazy loading, and would like to be able to prevent a request if one has not already been made. I more or less need to know as much as possible on this topic.
Specifically, in this particular case, the only place I can put JS is after the body, and we're not sure yet if converting every image to use data-src instead of src from the server is an option, so that may mean having to comb back through the DOM to figure out where everything is at, and try to cancel as much as possible without stopping anything that is already in progress, because that would cause redundancy (even though it may help metrics in a very dirty way).
BTW, we are not using browser-native lazy loading, because I've found that is only useful for a specific use case. It's can't really be relied upon for prioritizing images above the fold, since it loads some lazy elements below the fold before the window.load event fires. Which makes no sense to me (why it can't start doing that after window.load.) And why there are no options on the feature. Also why loading:lazy can't be set in CSS.
Here is an example of how to control image loading:
https://jsfiddle.net/xnp6hLr4/2/
Your best bet is to load images dynamically and keep track of their states (not loaded, loading, loaded)
var isLoaded = false;
$(document).ready(function(){
$('#image').one().bind('load',(function(){alert('loading complete'); isLoaded=true; }));
$('#startButt').click(function(){
if (isLoaded)
{
alert('Image already loaded');
}
else
{
alert('Loading start');
$('#image').attr('src', 'https://cdn.pixabay.com/photo/2022/08/31/11/01/kangaroo-7423042_960_720.jpg');
}
});
});
Sorry by this dummy question! :D
I´m trying to make a clickable map with html5 canvas element, I find this good example: http://www.rubydesigner.com/blog/click-map-using-html5-canvas
But when a download it (CTRL+S) from Chrome it doesnt work. It download the html page and files folder with the JS a images, I checked the path to the images, but still the map doesnt appear. What is the problem?
UPDATE
Initial assumption about CORS turns out to not be the case here.
The code seemed to work in Chrome and although CORS typically is the cause when downloading files and using canvas with local (file://) file references. As localhost is used here via XAMMP this won't be the cause and it turns out there are more than one bugs in the online code.
Specifically the way it calculates the coordinates for the mouse:
var datapos = ((e.offsetY-2) * 300 * 4) + ((e.offsetX-1) * 4);
This will result in a NaN value due to offsetX/Y which of course cannot be used for any index.
The more appropriate way is something like this, here also compensating for canvas offset:
var rect = map_wrapper.getBoundingClientRect();
var datapos = ((e.clientY - (rect.top |0)) * 300 * 4) +
((e.clientX - (rect.left|0)) * 4);
However, I have never came across a floating point position for an element which seem to be case here (rect.top shows a float value in my browser, another little surprise) and therefor I am forcing the value to integer here (normally not necessarily.. I didn't dig deep into this). As debugging the whole code is a bit out of the scope here I will leave it with that and to OP to locate other bugs.
Correcting the position will at least give a usable index for the pixel array which in turn will return a valid (not necessarily correct it turns out, which leave checking of image, tolerane in case gamma/color correction is applied....) value for the red component (still issues when testing but as said, it's a bit out of the scope to do a full debug and correction).
Hopefully this can lead you to where the other errors are. I did not go through the html etc.
Using PhantomJS V 1.8.1
Thanks in advance.
I am trying to run some tests on a website that I am developing which is using backbone.js.
One of my tests involve checking to see if a Canvas is present and clicking on it. My problem is that whatever selector I use to get the Canvas Element I cannot get the selector to find it. I use the same CSS selector in Google Chrome when viewing the page and all is OK. At first I thought that the issue may have been due to the element not being present on the page but other elements which are inserted with the canvas are present so I am 99% sure that this is not the problem.
The selectors I have tried to use are:
document.querySelectorAll('#idOfCanvas');
document.querySelectorAll('canvas#idOfCanvas');
Also if I use .classClassName:nth(1) to select the tyre selector, it still fails to work (works in Google Chrome though as does the other examples provided)
The canvas has a class name which is picked up by the selector by I would rather not use a class selector.
Any help would be much appreciated.
Cheers :)
Also
Like I mentioned I am almost certain that the Canvas exists as the container div for it exists. Also I have four elements on the page with the same className (two of which are canvases) and four elements are being returned when I run
return document.querySelectorAll('.className').length = 4;
Assuming you have something like this:
<canvas id="idOfCanvas"></canvas>
This should work:
canvas = document.getElementById("idOfCanvas");
// or
canvas = document.querySelector("#idOfCanvas"); // Only get the first match, ID's should be unique, any way.;
// or
canvas = document.querySelectorAll("#idOfCanvas")[0];
// or
canvas = document.getElementsByTagName("canvas")[0]; // Get the first <canvas> element.
However, you'll have to make sure your canvas element is actually loaded when the script is executed. Have a look at this onload tutorial, for example.
Try this :
canvas = document.getElementById(#IdOfCanvas:nth-child(1));
I would like to re-use a Request.JSON object, but I am not sure how. I'm looking for something like the following example:
// In initialize/constructor
this.request = new Request.JSON( {
method : 'get'
});
// Elsewhere
this.request.setOptions({
url : 'http://...',
onSuccess : onSuccess,
onFailure : onFailure
}).send();
there are going to be certain issues with this kind of approach.
if you only have the one instance handling all requests, then you need to make sure whilst a request is taking place, there is nothing else that can restart it with the new options as its asynchronous. additionally, events will stack up. every new instance that you run will addEvent onComplete/onSuccess/onFailure and they won't always be relevant. so you need to apply removeEvents() to the request instance before each run.
have a look here http://www.jsfiddle.net/dimitar/8a7LG/4/
i am not showing this as an example of how i'd write it but to see the problems that come with it. click the second link first then the first one (jsfiddle adds 2 seconds network lag) and you will see the alert from the second link's onComplete event stacked up on the first one as well. further more, for each click on link 2 you will see a new alert in addition to the old ones.
you must also consider how applicable it is to extend Request.JSON instead but it all depends on your needs.
p.s. if you go over to Request.JSONP this kind of structure may play some tricks, in particular with the callback functions being reset etc.
best of luck :)
edit here's the thing working with removeEvents so you don't get the stacking up: http://www.jsfiddle.net/dimitar/8a7LG/5/
I don't differ with the accepted answer's point, but it actually sidesteps the question IMHO.
Take a look at the following blog post (it's not mine); there, under the subtitle Multiple Links with Request.HTML you can find some guidance about how to reuse the Request instance.
http://ryanflorence.com/basic-ajax-and-json-requests-with-mootools/
In no way shape or form am i advertising/promoting my programming style, but as far as 'multiple variable declarations' are concerned, which case is more acceptable professionally and commonly:
case 1:
private $databaseURL = "localhost" ;
private $databaseUName = "root" ;
private $databasePWord = "" ;
private $databaseName = "AirAlliance";
case 2:
private $databaseURL = "localhost";
private $databaseUName = "root";
private $databasePWord = "";
private $databaseName = "AirAlliance";
The reason i like case 1 is because i can skim though it and see that all is correct way faster than case 2. Also i can visually get familiar with variable names witch makes it faster to work with them l latter on the program.
Whichever style the project is already using, so you don't end up spending all day fixing every file you touch.
case 1.5:
private $databaseURL = "localhost";
private $databaseUName = "root";
private $databasePWord = "";
private $databaseName = "AirAlliance";
I don't think aligning the semicolons makes it any more readable, it just makes it annoying to change the value of one of the strings and then have to add or delete spaces to line up the semicolons all over again.
In this case, it looks like the variable names are unlikely to change, so it should be OK to line up the equals signs. If it were possible that the variable names would change, however, I would go with case 2 because (again) it would be annoying to have to line everything up again. (Imagine the work involved in simply adding a new variable called $databaseLongVariableName.)
Case 2. When you add a new variable to your "group", or add/remove a character on one of those lines, you won't have to spend time fiddling around trying to make things line up.
If you change all their alignments when you add a new variable, then any diff tool will show up multiple changes there. Just a thought.
Also, I've done this once. It became a pain in the ass when I had to add a variable that was longer. Padding out all the existing ones with spaces to match turned me off this technique.
Interesting question. As far as I'm concerned, there's no good reason to use case 1. I've never seen that style before, except possibly in config files, and it costs extra time to format your code properly. As soon as you change the contents of the variable, you have to reset your semi-colon as well.
It only works if you use spaces as well... anyone using tabs might have different tab stops set, so it will look completely different opened in another editor.
I think the advantage of readability you mention is somewhat offset by the extra effort required to write it.
It's very tempting to nicely align stuff, I used to align my accessors in PHP as so
function getName() { return $this->name; }
function getAge() { return $this->age; }
function getHeight(){ return $this->height; }
The problem comes when you add in a longer line:
function getName() { return $this->name; }
function getAge() { return $this->age; }
function getNiNumber(){ return $this->ni_number; }
function getHeight(){ return $this->height; }
If I edit the three other lines, then when I commit my change it makes it harder to see who wrote a particular line, and in which revision they did it.
Aligning stuff like = and ; just invites a whole big mess of tab-space screw ups that get checked in, then have to be fixed later.
Most people will use tabs to the left of a line for indentation, then use spaces to align stuff to the right.
Beyond adding bloat to files, it just becomes a big, inconsistent soupy mess. To me, it does not make the code any more readable. To some editors, it makes the code even less readable.
Use case 2. That is far more standard: Google C++ Style
Really you shouldn't even concern yourself with this. Your editor should automatically autoformat your code. Try ctrl+shift+F in Eclipse.
Aligning the semicolons seems like wasted time to me, unless your IDE/text editor can do it for you. Especially if you later add another entry longer than the previous ones; you'll have to realign all of them.
I just fired up my editor and it just hit me. all the reasons i like case 1 for are in syntax highlighting without wasting time.
case 2. with anything else your version control will go crazy everytime you re-adjust the spacing. besides with IDEs that has highlighting and some also show a variable listing, its really a waste of time to align '=' and ';' in my opinion.
Case 2. If I leave out a semicolon, I have a program that tells me so. It's the compiler.
Going with what ever the project you are working on is the best option. (If the project doesn't have a set of coding guidelines, spending five minutes to define them is highly recommended).
A lot of the larger programs have tools which scan the code looking for things to sort and clean. Adding whitespace at the end of the variable could affect some of them.
Also regarding tabs, I've never worked on a project that didn't determine the tab spacing for the editing. You can always use your personal one and have a precommit hook to edit the file before it goes in, but messing with tab spacing will annoy people no end.
You can have a look at the book "Expert PHP 5 Tools" for better understanding the code styling in more detail way.
*There is e-book in net *