Asynchronous image loading - javascript

I'm creating a Hangman game for a project. I have most of the functionality I need, however I am having one issue. When the last incorrect guess is made, it displays the alert box telling you you've lost, before loading the image. I want the image to load first and then the alert box.
I realize that the issue is with the way the DOM loads elements and that I should create a callback function in jQuery.
This is the line in my code that changes the image, and it works fine until it gets to the last one.
document.getElementById("gallows").src = displayGallows[incorrectGuesses - 1];
I have tried using a Jquery function to get this working but my knowledge of jQuery is pretty much non-existent.
var img = $("gallows");
img.load(function() {
alert("Unlucky, you lost. Better luck next time!");
});
img.src = displayGallows[incorrectGuesses - 1];
I have compared this to many posts I have found online and to my untrained eye, it looks OK. When I was troubleshooting I did realize that the img.src was assigned the correct value but the image didn't appear on my page or didn't fire the alert box.
This led me to believe that it may be an issue with linking to the jquery.js file. I have an HTML page that references the jQuery file in it's head tag.
<head>
<title>Hangman</title>
<link rel="stylesheet" href="base.css"/>
<script src="jquery.js"></script>
<script src="hangman.js"></script>
<script src="home.js"></script>
</head>
The file I am writing my JavaScript and jQuery from is the hangman.js file.
Do I also need to refer to the jquery.js file from the hangman.js file? While reading up on this I found that I may have to do this, so I've tried this:
///<reference path="jquery.js" />
and this
var jq = document.createElement('script');
jq.src = 'jquery.js';
document.getElementsByTagName('head')[0].appendChild(jq);
but to no avail, though I don't really understand the second one, as I found these examples on the internet.
Note that in my home.js file I have simple a simple jQuery function to em-bold the text on a button when you mouseover it and this works OK.
If anyone could help me out or point me in the right direction that would be great.

Your best bet here is probably not to use alert at all; instead, use modern techniques like an absolutely-positioned, nicely-styled div to show your message. Showing that won't get in the way of the browser showing the image once it arrives, whereas alert basically brings the browser to a screeching halt until the user clicks the alert away.
But if you want to use alert:
Your concept of waiting for the load event from the image is fine, but you may want to yield back to the browser ever-so-briefly afterward to give it a chance to display the image.
Not using jQuery, as you don't appear to be using it otherwise:
var img = document.getElementById("gallows");
img.onload = img.onerror = function() {
setTimeout(function() {
alert(/*...*/);
}, 30); // 30ms = virtually imperceptible to humans
};
img.src = displayGallows[incorrectGuesses - 1];
That waits for the load or error event from the image, then yields back to the browser for 30ms before showing the alert.
But if you pre-cache the images, you can make the load event fire almost instantaneously. Most browsers will download an image even if it's not being shown, so if you add
<img src="/path/to/incorrect/guess.png" style="display: none">
...to your page for each of the incorrect guess images, then when you assign the same URL to your #gallows image, since the browser has it in cache, it will load almost instantly. Here's an example using your gravatar and a 30ms delay after load: http://jsbin.com/fazera/1

Firstly, to get an object by ID in jQuery, you have to use #.
var img = $("#gallows");
You can not use src or other "vanilla" properties directly on a jQuery object. You can, however do any of these:
Get the actual element from the jQuery object.
var img = $("#gallows");
img.load(function() { ... }
img[0].src = "image.jpg"; // First element in jQuery object
Use the jQuery method attr (recommended).
var img = $("#gallows");
img.load(function() { ... }
img.attr("src", "image.jpg");
Get the element just like you do now.
var img = document.getElementById("gallows");
img.onload = function() { ... }
img.src = "image.jpg";

please make sure that you have your jQuery code that's within the HEAD tag, inside:
$( document ).ready(function() { ...your jQuery here... });
More info: Using jQuery, $( document ).ready()
Your question: "Do I also need to refer to the jquery.js file from the hangman.js file?"
No, but place <script src="hangman.js"></script> tag in the header after referring to your jQuery file:
<head>
<script src="jquery_version_that_you_are_using.js"></script>
<script src="hangman.js"></script>
<script>
$( document ).ready(function() {
//Your jQuery code here
});
</script>
</head>

Related

Initialize more than one html element using jQuery and Javascript

I have tried to lead my html element to fire my customized JS file's method.
Third textarea appears nicely.
First and second textareas does not effect any of the settings i am trying to change in myJSFile.js file.
Here's my problem : js file loads the last textarea nicely, but cannot initialize previous ones properly using my js methods.
I'm doing something wrong with my JS file, and i'd appreciate if you help me.
P.S. : Initalizing some plugin and working on CKEditor.
Here's my HTML file :
<textarea id="myTextAreaID" name="myTextArea"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID')"></script>
<textarea id="myTextAreaID2" name="myTextArea2"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID2')"></script>
<textarea id="myTextAreaID3" name="myTextArea3"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID3')"></script>
Here's myJSFile.js file
var textAreaID;
$(function(){
var myTextArea = $('#'+textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param){
textAreaID = param;
}
Thanks in advance.
This is not very good idea to do it like this, however it's interesting to understand why it happens. In your code below you are defining global variable textAreaID:
var textAreaID;
$(function() {
var myTextArea = $('#' + textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param) {
textAreaID = param;
}
This script is injected three times into document. After the last script tag the value of textAreaID variable will be myTextAreaID3, because it's global and the last setTextAreaParameters invocation will override previous. Remember that scripts are loaded synchronously in your case (no async or deferred attribute), it means that onload callbacks don't wait and immediately set textAreaID to new values.
However DOMContentLoaded event has not yet fired. This is the event you are subscribing with this code:
$(function() {
// DOMContentLoaded
});
When it eventually does - only the third textarea will be processed - the one with id myTextAreaID3.
Better approach would be to have only one script tag and set textareas the same className attribute:
<textarea id="myTextAreaID2" name="myTextArea2" class="editor"></textarea>
Then in the script probably have some sort of map with configuration parameters for each individual textarea.
You are including the same script three times, but the browser is probably smart enough to only load it once (no reason to load the same script on the same page more than once).
What you need to do is to include the script only once, say before the end of the body tag
...
<script type="text/javascript" src="../public/js/myJSFile.js"></script>
</body>
and then in the JS file, wait for the document to load, and handle all text areas accordingly:
$(function() {
$('textarea').each(function(i, j) {
console.log('do something for the ' + i + 'th text area');
});
})

$("<img/>").attr("src",something).load() not supported in IE < 9?

http://jsfiddle.net/DerekL/qDqZF/
$('<img/>').attr('src', "http://derek1906.site50.net/navbar/images/pic3.png").load(function() {
$("body").html("done");
blah blah blah...
})
There I have tested using $("<img/>").load in IE 7, and what I got are these:
When run in counsel, I get this:
"Unable to get value of the property 'attr': object is null or undefined"
When used in my webpage, I get this:
"SCRIPT5007: Unable to get value of the property 'slice': object is null or undefined"
jquery.js, line 2 character 32039
What happened? (Hate IE...)
Ensure that the load function is being executed. I recently dealt with this issue. In IE the load function wasn't firing on cached images. For my purposes I was able to get around this by never allowing the image to cache. ( An ugly solution )
ex:
src="loremIpsum.jpg"
change to:
src="loremIpsum.jpg?nocache=" + new Date().getTime()
Where "nocache" can be changed to anything that makes sense to you.
From the jQuery documentaion:
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache"
http://api.jquery.com/load-event/
In IE the load event doesn't always get triggered when the image is cached. Try this:
var img = new Image();
img.src = "http://derek1906.site50.net//navbar/images/pic3.png";
if (img.complete || img.readyState === 4) {
$("body").html("done");
}
else {
$(img).on("load error onreadystatechange",function(e){
if (e.type === "error") {
$("body").html("Image failed to load.");
}
else {
$("body").html("done");
}
});
}
Also, don't forget to wait for the DOMReady event, otherwise $("body") may not exist yet if the image loads fast enough.
jsFiddle
Edit:
I have a plugin that may help simplify image preloading: https://github.com/tentonaxe/jQuery-preloadImages/
So I did some quick testing in jfidde, and pulled out the relevant code and ran it standalone in ie7-8-9. They all ran fine. I can say with confidence that it is not this piece of code that is breaking your page.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo by DerekL</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript'>
$('<img/>').attr('src', "http://derek1906.site50.net//navbar/images/pic3.png").load(function() {
$("body").html("done");
$("<img/>").appendTo("body").attr("src","http://derek1906.site50.net//navbar/images/pic3.png");
});
</script>
</head>
<body>
Loading...
</body>
</html>
Some ideas though:
Wrap any script in the document head that manipulates the DOM in a document.ready call.
$(document).ready(function(){ go(); });
Search your source code for that slice call. If you are trying to manipulate a jQuery collection with .slice() it will break. jQuery collections are Objects, not Arrays. (may or may not be your problem)
Make sure that any code trying to touch that image is called after the .load() method returns. A common mistake is to do something like:
$('<img id="me" />').attr('src', 'my.jpeg')
.load( function(){ $(this).appendTo("body"); } );
alert( $('#me').attr('src') );
If this is the only image on the page, the above script will likely fail because the appendTo() is called asyncronously, and almost certianly after the following lines of code have executed and failed. Make sure that any logic manipulating that image is run from the .load() callback. (As you have nicely done in your above example code.)
If you paste the rest of your page source I can take a look! Good luck!
add load event first then set img'src
because ie run so fast than when you set the src, "load" event was finished
the new load handler will be executed next change

Trying to load an API and a JS file dynamically

I am trying to load Skyscanner API dynamically but it doesn't seem to work. I tried every possible way I could think of and all it happens the content disappears.
I tried console.log which gives no results; I tried elements from chrome's developers tools and while all the content's css remains the same, still the content disappears (I thought it could be adding display:none on the html/body sort of). I tried all Google's asynch tricks, yet again blank page. I tried all js plugins for async loading with still the same results.
Skyscanner's API documentation is poor and while they offer a callback it doesn't work the way google's API's callback do.
Example: http://jsfiddle.net/7TWYC/
Example with loading API in head section: http://jsfiddle.net/s2HkR/
So how can I load the api on button click or async? Without the file being in the HEAD section. If there is a way to prevent the document.write to make the page blank or any other way. I wouldn't mind using plain js, jQuery or PHP.
EDIT:
I've set a bounty to 250 ontop of the 50 I had previously.
Orlando Leite answered a really close idea on how to make this asynch api load although some features doesn't work such as selecting dates and I am not able to set styling.
I am looking for an answer of which I will be able to use all the features so that it works as it would work if it was loading on load.
Here is the updated fiddle by Orlando: http://jsfiddle.net/cxysA/12/
-
EDIT 2 ON Gijs ANSWER:
Gijs mentioned two links onto overwriting document.write. That sounds an awesome idea but I think it is not possible to accomplish what I am trying.
I used John's Resig way to prevent document.write of which can be found here: http://ejohn.org/blog/xhtml-documentwrite-and-adsense/
When I used this method, I load the API successfuly but the snippets.js file is not loading at all.
Fiddle: http://jsfiddle.net/9HX7N/
I belive what you want is it:
function loadSkyscanner()
{
function loaded()
{
t.skyscanner.load('snippets', '1', {'nocss' : true});
var snippet = new t.skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
}
var t = document.getElementById('sky_loader').contentWindow;
var head = t.document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange= function() {
if(this.readyState == 'complete') loaded();
}
script.onload= loaded;
script.src= 'http://api.skyscanner.net/api.ashx?key=PUT_HERE_YOUR_SKYSCANNER_API_KEY';
head.appendChild(script);
}
$("button").click(function(e)
{
loadSkyscanner();
});
It's load skyscanner in iframe#sky_loader, after call loaded function to create the SearchPanelControl. But in the end, snippet draws in the main document. It's really a bizarre workaround, but it works.
The only restriction is, you need a iframe. But you can hide it using display:none.
A working example
EDIT
Sorry guy, I didn't see it. Now we can see how awful is skyscanner API. It puts two divs to make the autocomplete, but not relative to the element you call to draw, but the document.
When a script is loaded in a iframe, document is the iframe document.
There is a solution, but I don't recommend, is really a workaround:
function loadSkyscanner()
{
var t;
this.skyscanner;
var iframe = $("<iframe id=\"sky_loader\" src=\"http://fiddle.jshell.net/orlleite/2TqDu/6/show/\"></iframe>");
function realWorkaround()
{
var tbody = t.document.getElementsByTagName("body")[0];
var body = document.getElementsByTagName("body")[0];
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
}
function snippetLoaded()
{
skyscanner = t.skyscanner;
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
setTimeout( realWorkaround, 2000 );
}
var loaded = function()
{
console.log( "loaded" );
t = document.getElementById('sky_loader').contentWindow;
t.onLoadSnippets( snippetLoaded );
}
$("body").append(iframe);
iframe.load(loaded);
}
$("button").click(function(e)
{
loadSkyscanner();
});
Load a iframe with another html who loads and callback when the snippet is loaded. After loaded create the snippet where you want and after set a timeout because we can't know when the SearchPanelControl is loaded. This realWorkaround move the autocomplete divs to the main document.
You can see a work example here
The iframe loaded is this
EDIT
Fixed the bug you found and updated the link.
the for loop has gone and added a while, works better now.
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
For problematic cases like this, you can just overwrite document.write. Hacky as hell, but it works and you get to decide where all the content goes. See eg. this blogpost by John Resig. This ignores IE, but with a bit of work the trick works in IE as well, see eg. this blogpost.
So, I'd suggest overwriting document.write with your own function, batch up the output where necessary, and put it where you like (eg. in a div at the bottom of your <body>'). That should prevent the script from nuking your page's content.
Edit: OK, so I had/took some time to look into this script. For future reference, use something like http://jsbeautifier.org/ to investigate third-party scripts. Much easier to read that way. Fortunately, there is barely any obfuscation/minification at all, and so you have a supplement for their API documentation (which I was unable to find, by the way -- I only found 'code wizards', which I had no interest in).
Here's an almost-working example: http://jsfiddle.net/a8q2s/1/
Here's the steps I took:
override document.write. This needs to happen before you load the initial script. Your replacement function should append their string of code into the DOM. Don't call the old document.write, that'll just get you errors and won't do what you want anyway. In this case you're lucky because all the content is in a single document.write call (check the source of the initial script). If this weren't the case, you'd have to batch everything up until the HTML they'd given you was valid and/or you were sure there was nothing else coming.
load the initial script on the button click with jQuery's $.getScript or equivalent. Pass a callback function (I used a named function reference for clarity, but you can inline it if you prefer).
Tell Skyscanner to load the module.
Edit #2: Hah, they have an API (skyscanner.loadAndWait) for getting a callback once their script has loaded. Using that works:
http://jsfiddle.net/a8q2s/3/
(note: this still seems to use a timeout loop internally)
In the skyrunner.js file they are using document.write to make the page blank on load call back... So here are some consequences in your scenario..
This is making page blank when you click on button.
So, it removes everything from page even 'jQuery.js' that is why call back is not working.. i.e main function is cannot be invoked as this is written using jQuery.
And you have missed a target 'div' tag with id = map(according to the code). Actually this is the target where map loads.
Another thing i have observed is maps is not actually a div in current context, that is maps api to load.
Here you must go with the Old school approach, That is.. You should include your skyrunner.js file at the top of the head content.
So try downloading that file and include in head tag.
Thanks

load specific image before anything else

I'm a creating a loading screen for website I am making. The website loads many images, scripts, etc. The HTML and CSS part is great, but I need a way to guarantee that the "loading..." image will be loaded before anything else.
I'm using jQuery, and everything is initiated within $(function () { ... });. I imagine that the code for this would need to be called before/outside that block, and the code to remove the loading screen will be called at the very end of that block. Currently, the loading image is set as a DIV background, which is the way I prefer it. However, if it's completely necessary, I will settle for an IMG tag.
Update: (solution)
I was able to answer my own question by using a combination of Robin and Vlad's responses. Both were very good, and excellent answers, however the problem is that they were aimed to load an image before another image, rather than load an image before anything else. (CSS, JS, etc...)
Here's the dirty version of what I came up with:
var files = [new Image(), document.createElement('link'), document.createElement('script')];
files[0].setAttribute('src', 'images/loading.gif');
files[1].setAttribute('rel', 'stylesheet');
files[1].setAttribute('type', 'text/css');
files[1].setAttribute('href', 'test.css');
files[2].setAttribute('type', 'text/javascript');
files[2].setAttribute('src', 'js/jquery-1.5.1.min.js');
window.onload = function (e) {
document.getElementsByTagName('head')[0].appendChild(files[1]);
document.getElementsByTagName('head')[0].appendChild(files[2]);
}
Taking a look at the load sequence on the network tab of Chrome's developer console shows that 'loading.gif' is loaded first, then 4 dummy images, then 'test.css', and then 'jquery.1.5.1.min.js'. The CSS and JS files don't begin to load, until they've been inserted into the head tag. This is exactly what I want.
I'm predicting that I may begin to have some problems, however, when I begin to load a list of files. Chrome reports that sometimes the JS file is loaded first, but the majority of the time the CSS file is loaded first. This isn't a problem, except when I begin to add files to load, I will need to ensure that jQuery is loaded before a script file that uses jQuery.
If anyone has a solution for this, or a way to detect when the CSS/JS files are finished loading, using this method, then please comment. Though, I'm not sure that it's going to be a problem yet. I may need to ask a new question in the future about this, if I start to run into problems.
Thank you to every who has helped with this issue.
Update: (glitch fix)
I ended up running into a lot of problem with this method, because the script files were being loaded asynchronously. If I would clear the browser cache, and then load the page, it would finish loading my jquery dependent files first. Then if I refreshed the page, it would work, because jquery was loaded from cache. I solved this by setting up an array of files to load, then putting the load script into a function. Then I would step through each array item using this code:
element.onload = function() {
++i; _step();
}
element.onreadystatechange = function() {
if (("loaded" === element.readyState || "complete" === element.readyState)) { ++i; _step(); }
}
You can reuse resource prealoding browser support.
I'm not sure it works across all browsers but in my case this approach helps me to load images first. Also it allows to define concrete images so UI specific could be skipped
First define in header what resource you want to preload and define resource priority
<link rel="preload" href="link-to-image" as="image">
or
<link rel="preload" href="link-to-image">
Second line allow to increase loading priority across all object types (scripts / images / styles). First line - only through images.
Then define in body link to image as usual:
<img src="link-to-image" alt="">
Here is my working example
https://jsfiddle.net/vadimb/05scfL58/
As long as the "loading..." image is positioned before any other html elements, it should load first. This of course depends on the size of the image. You could put the loading div right after the tag and position it using 'position:absolute'.
Regarding the code to remove the loading screen, one method is to do the following.
Put all the images, scripts that need to be loaded in a hidden div (display: none)
Set up a variable that will hold the total of the images / scripts to be loaded
Set up a counter variable
Attach to each image / script the "onload" event
Everytime the "onload" event is triggered it will call a function that will increment the counter variable and check if the value of the counter equals the value of the total variable
If all resources have been loaded, fire a custom event that will show the div with the images, and hide the div with the loading screen.
The code below isn't tested so it might not work. Hope it helps
var totalImages = 0;
var loadCounter = 0;
function incrementLoadCounter() {
loadCounter++;
if(loadCounter === totalImages) {
$(document).trigger('everythingLoaded');
}
}
function hideLoadingScreen() {
$('#loadingScreen').hide();
$('#divWithImages').show();
}
$(document).ready(function(e) {
$('#loadingScreen').bind('everythingLoaded', function(e) {
hideLoadingScreen();
});
var imagesToLoad = $('img.toLoad');
totalImages = imagesToLoad.length;
$.each(imagesToLoad, function(i, item) {
$(item).load(function(e) {
incrementLoadCounter();
})
});
})
I'm not sure if it's possible to enforce.
If it is, try adding this in the head-tag:
<script type="text/javascript">
if(document.images)
(new Image()).src="http://www.image.com/example.png";
</script>
In theory that may load and cache that image before anything else.
I think if you place the IMG tag at the top of your html body it will be loaded first. If you do not want to move your div just use a copy of the image tag. Once the images is loaded it will be shown in every image tag which shows the same picture.
Or you could use spin.js as loading image. It display this "loading cycle image" via javascript.
Check it out under:
http://fgnass.github.com/spin.js/

jQuery ready() and script sequence

I'm an jQuery noob and I'm wondering how fix this issue:
I have an external .js script, let's take reflection.js as example.
Reflection.js creates canvas reflection for every class="reflect" image.
I'm appending a few images trough different JS script that starts when ('document').ready.
Of course reflection.js doesn't work for images created by the script above.
How to avoid that?
I guess I'll need callback (?). Unfortunately I'm not getting idea of callbacks idea even after reading documentation.
[edit]
<script src="js/reflection.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery().ready(function() {
jQuery('#thumbs li').each(function(){
jQuery('.'+id+' a').append('<img src="' + imgURL + '" class="reflect" /></a>');
});
});
</script>
Image loading events do not bubble. You cannot hook into those.
Since your images have the class "reflect" it means you have some control over the source. So I recommend your reflection code publishes an API for you to call.
window.Reflect = function(img) {
...
};
...
var img = $("<img></img");
img.attr({
...
});
Reflect(img);
...
If you do not want to do this then you can poll the document for new images.
(function poll() {
var images = $("img.reflect");
...
images.removeClass("reflect")
setTimeout(poll, 500);
})();
If I understand this correctly, you have 2 functions under "ready" sequence and one script depends on other.
The way how I solved this problem, I have build my own includeJS as well as additional ready-checking layer on top of the one which jQuery has.
https://github.com/atk4/atk4/blob/master/templates/js/start-atk4.js
So my code looks like this:
$(function(){
$.atk4.includeJS('reflection.js');
$.atk4.includeJS('different.js');
$.atk4(function(){
$('.reflect').reflection();
});
});
What happens is, after document is ready, jQuery launches above code. It appends 2 scripts and evaluates them (by adding tag). When evaluation is complete, function atk4.get will execute readiness chain very similar to how jQuery does it.

Categories