We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

HTML5 JavaScript APIs

00:00

Formal Metadata

Title
HTML5 JavaScript APIs
Subtitle
The Good, The Bad, The Ugly
Title of Series
Number of Parts
150
Author
License
CC Attribution - NonCommercial - ShareAlike 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
The name “HTML5” is misleading – actually, most of the new features around HTML5 are hidden in JavaScript APIs. This session will develop many code samples showcasing many of the interesting and useful HTML5 features, including some APIs that are related to HTML5, but are actually not part of the standard. We will tackle Geolocation, offline scenarios, webworkers, real-time communication with websockets, and much more.
Software developerExecution unitComputer-assisted translationDrop (liquid)Element (mathematics)Form (programming)Streaming mediaSlide ruleCASE <Informatik>Element (mathematics)Computer programmingForm (programming)Formal languageText editorValidity (statistics)Latent heatMultiplication signWeb 2.0CodeTelecommunicationProgramming languageOrder (biology)Moment (mathematics)BitOffice suiteMereologySelf-organizationMobile WebMusical ensembleNumberWeb browserAsynchronous Transfer ModeDecision theoryComputer virusPosition operatorMechanism designSet (mathematics)Goodness of fitDrag (physics)Uniform resource locatorArmRepetitionJava appletExtension (kinesiology)MathematicsVector potentialScripting languageCovering spaceDrop (liquid)Process (computing)Graphical user interfaceXMLUMLComputer animation
Meta elementHost Identity ProtocoloutputForm (programming)Data typeScripting languageForm (programming)Address spaceInformationCategory of beingObject (grammar)ResultantType theoryEmailVideo game consoleWeb browserSemantics (computer science)Field (computer science)Speech synthesisValidity (statistics)CASE <Informatik>Mobile appElement (mathematics)Pattern recognitionWebsiteoutputGame theoryPosition operatorGroup actionComputing platformError messageApplication service providerWeb 2.0Standard deviationFile formatOrder (biology)BitSystem callNavigationTwitterFunction (mathematics)Coordinate systemGoodness of fitMarkup languageRegular graphGoogolFlow separationMoment (mathematics)PrototypeComputer programmingArmScripting languageInstance (computer science)Matrix (mathematics)MeasurementGraphical user interfaceRange (statistics)Uniform resource locatorGeometryJava appletState of matterAreaBuildingFacebookProcess (computing)Right angleEnvelope (mathematics)Multiplication signSoftware testingComputer animation
Source codeComputer networkVideo game consoleElement (mathematics)CurvatureError messageMountain passCapability Maturity ModelMeta elementScripting languageEmailView (database)Service (economics)GoogolKey (cryptography)Moment (mathematics)MeasurementPosition operatorSet (mathematics)Instance (computer science)Disk read-and-write headResultantGoodness of fitSelf-organizationElectronic mailing listSpectrum (functional analysis)Game theoryGroup actionServer (computing)Cartesian coordinate systemPoint (geometry)Uniform resource locatorConnected spaceCASE <Informatik>ArmAddress spaceVirtual machineHypermediaInformationProcess (computing)IP addressSoftwareTerm (mathematics)AverageVector potentialAreaMultiplication signDifferent (Kate Ryan album)Data storage deviceVideo game consoleWeb browserScripting languageOperating systemBitComputer programmingFamilyReal numberInternetworkingGraphical user interfaceCuboidValidity (statistics)Sinc functionForm (programming)CodeLocation-based serviceCoordinate systemComputer animation
Point (geometry)Computer-assisted translationDrop (liquid)Element (mathematics)World Wide Web ConsortiumWeb browserData storage deviceCache (computing)Latent heatSoftware developerServer (computing)HTTP cookieWeb 2.0Order (biology)Cartesian coordinate systemLocal ringPlanningLaptopSoftwareBitSet (mathematics)WebsiteMedical imagingConnected spaceInternetworkingRevision controlMultiplication signWeb applicationGoogolVideo gameWave packetUniform resource locatorInformationStructural loadClosed setInstance (computer science)Scheduling (computing)Electronic mailing listService (economics)Workstation <Musikinstrument>SummierbarkeitSource codeReal numberRight angleThumbnailSuite (music)Computer programmingArmComputer animation
Function (mathematics)Line (geometry)Discrete element methodMeta elementScripting languageVideo game consoleDrum memoryData typeComputer fileSoftwareCartesian coordinate systemMixture modelWeb 2.0Complex (psychology)Connected spaceWeb browserUniform resource locatorNavigationEmailMappingAbsolute valueNumberRandomizationBitMultiplication signArithmetic meanSquare numberService (economics)Software testingLocal ringMobile appMathematicsVariancePlanningImage resolutionDirect numerical simulationNeuroinformatikServer (computing)Physical systemOrder (biology)Multitier architectureInformationCalculationWindowCore dumpCodeComputer architectureInstance (computer science)CASE <Informatik>Process (computing)Line (geometry)TelecommunicationScripting languageVideo gameJava appletArmBit rateRandom number generationAddress spaceMechanism designRight angleCoefficient of determinationSound effectComputer animation
Scripting languageMeta elementVirtual machineCalculationMessage passingUsabilityScripting languageMultiplication signData storage deviceError messageComputer animation
Menu (computing)Web browserWebsiteCASE <Informatik>Complex (psychology)Demo (music)CalculationError messageMultiplication signLatent heatResultantScripting languageCodeArithmetic meanMessage passingSimilarity (geometry)Endliche ModelltheorieInformationThread (computing)Real numberComputer animation
Menu (computing)Data typeComputer fileHash functionMeta elementScripting languageRandom numberArmFunction (mathematics)Message passingMathematicsHTTP cookieSystems engineeringVideo game consoleWeb pageCross-site scriptingNetwork socketCodeThread (computing)Event horizonMessage passingWeb browserEndliche ModelltheorieDifferent (Kate Ryan album)Set (mathematics)CASE <Informatik>Server (computing)Computer fileRight angleMultiplication signConnected spaceCalculationTelecommunicationReal-time operating systemExtension (kinesiology)InformationResultantParameter (computer programming)Structural loadMechanism designDuplex (telecommunications)Web 2.0Scripting languageSystem callPattern languageBlock (periodic table)Dependent and independent variablesSummierbarkeitArithmetic progressionReal numberFacebookError messageTerm (mathematics)Video game consoleLatent heatContent (media)Flow separationOpen setUsabilityCartesian coordinate systemDemo (music)Lie groupDivisorWordService (economics)Film editingSoftware testingTap (transformer)BitGraph coloringDirection (geometry)Product (business)Coefficient of determinationMatrix (mathematics)Wave packetSocket-SchnittstelleJava appletCausalityIntelCycle (graph theory)WebsiteProfil (magazine)RootAreaDot productTouchscreenKey (cryptography)Instance (computer science)Logic gateComputer animation
Network socketFingerprintGamma functionServer (computing)Function (mathematics)Menu (computing)Message passingData typeMeta elementScripting languageRandom numberDisk read-and-write headVideo game consoleTorusHTTP cookieWeb pageEvent horizonDefault (computer science)Lemma (mathematics)Twin primeDemo (music)Server (computing)Structural loadIdentity managementConnected spaceDrop (liquid)CodeProcess (computing)Order (biology)Revision controlTelecommunicationModule (mathematics)Event horizonRegular graphDependent and independent variablesMessage passingRandom number generationComputer fileSystem callGoodness of fitElement (mathematics)Communications protocolClient (computing)Exclusive orState of matterDrag (physics)Default (computer science)Multiplication signInformation securityMechanism designOverhead (computing)Point (geometry)File systemFinite-state machineVideo game consoleSet (mathematics)CASE <Informatik>InternetworkingScripting languageAsynchronous Transfer ModeRepetitionNumberGroup actionWebsiteSocket-SchnittstelleInstallation artVideo gameService (economics)Virtual machineDirection (geometry)QuicksortNetwork socketRegulator geneSoftware developerFilm editingMeasurementInstance (computer science)View (database)Value-added networkFrustrationEndliche ModelltheorieParameter (computer programming)Web 2.0Physical lawFlow separationMetropolitan area networkComputer animation
Lemma (mathematics)Random numberMessage passingMeta elementScripting languageSupersonic speedSolid geometryFunction (mathematics)Form (programming)Junction (traffic)Event horizonComputer fileHeat transferComputer configurationCross-site scriptingEvent horizonDrag (physics)PropagatorDrop (liquid)Default (computer science)Computer filePlanningElectronic mailing listCategory of beingMechanism designWeb browserMetadataIterationDivision (mathematics)Selectivity (electronic)Web pageCASE <Informatik>InformationData transmissionPixelSolid geometryElectronic visual displayComputer configurationPhysical systemOrder (biology)Finite-state machineStreaming mediaDigital photographyFile systemSound effectMultiplication signReal numberArrow of timeType theorySocial classVarianceAreaSlide ruleWritingElement (mathematics)WindowSoftware frameworkContent (media)Hacker (term)Medical imagingGraph coloringUser interfaceFunctional (mathematics)Point (geometry)Coefficient of determinationPhysical lawFlow separationReading (process)Object (grammar)Formal grammarState of matterGodService (economics)ForestVirtual machineLengthPower (physics)Bit rateMetreInstance (computer science)BitRight angleInstant MessagingOffice suiteConstructor (object-oriented programming)Arithmetic meanCartesian coordinate systemCycle (graph theory)Computer animation
Computer-assisted translationDrop (liquid)Element (mathematics)Form (programming)TrailResultantCartesian coordinate systemForm (programming)BitTelecommunicationWeb 2.0MereologyReal numberEmailMusical ensembleComputer animation
Software developerComputer animationXMLUML
Transcript: English(auto-generated)
All right. Good morning. OK, a lot of people have been at the party tonight. OK, so let's try again. Good morning. OK, good morning. Hello. And thanks for showing up so early. So for those watching this later on the stream or on demand,
it's currently Friday, last conference day of NDC Oslo, 2013, 9 a.m. And yesterday night was the big party with a lot of bands and some light beers as well, as I've heard. I mean, I left the party early in order to be in top form this morning.
And well, not everybody in this room probably did that, too. But thanks anyway for showing up so early because I think this is going to be both an interesting talk and a fun talk. We originally planned on having the talk a little bit earlier in the program, but we thought it would be an excellent start in the final day
because it's an important topic. It's also a topic where, well, we can discuss and rant a little. And so this should be both interesting and fun and definitely worth your time. So my name is Christian Wentz. I'm one of the owners of a web agency with offices in Munich, Germany and London, UK.
And then I also do quite a bit of consulting with companies. Always on various web topics at the moment. I do quite a bit on mobile web and web performance. And about 15 years ago, I wrote a book on JavaScript.
And since 15 years ago, everybody was laughing at me because I was working with the children's language where you cannot write any good code and which doesn't have any features because it was once created to do form validation. Well, that's basically the only use case JavaScript ever had. Now, this has significantly changed, of course,
because now we have HTML5. Now, HTML doesn't really sound like a programming language. Well, actually it isn't, right? But most of the things that are interesting about HTML5 is not markup. Instead, the interesting things about HTML5 are the programming APIs that are either part of HTML5
or part of another specification or a specification to be in a decade or so that is already supported in modern browsers. So what I'd like to do today is I'd like to show you some of the JavaScript APIs. So just give you some ideas what is possible,
what eventually will be possible, and what you should definitely avoid. So I tried to find some good, some bad, and some really ugly examples and give you a really good overview here to give you some ideas for the way back home which you might want to implement in your applications or not. And I will also, of course, mention
which of those we have implemented, why we did so, and if we were happy with our decision. All right, we have quite a number of slides to go through, so I better get started. No, actually, I do have a slide deck which I'll also send to the organizers so you will be able to download it.
But I don't want to waste any time in slides. I want to waste time in the editor. So we just write some code, see if it runs, and then discuss why the code ran or why it did not run. I mean, I got one more slide, and the slide is just kind of a potential agenda, topics which we could cover today.
And some of the really interesting features of HTML5, and I like to cover most of them, at least to some extent, are those. So we do have new form elements. Actually, there is some HTML in HTML5.
Surprise, surprise. But apart from that, we have features like determining the position of the user, and we'll try that out, how well it works here in that room. We have some new approaches and mechanisms for online and offline scenarios. We have a mechanism called Web Worker,
which is part of a whole set of communication APIs. We even have drag-and-drop, and we have much more. Well, drag-and-drop, I hope you come to that point, because drag-and-drop, this will put me into ultra-rant mode. But let's wait until we do. So what do we got?
Actually, we got form elements. So I'm certainly excited to see some new form elements. So how about this? Input X WebKit, so we know it works in Chrome, and it will later work in Opera, since they now adopt WebKit as well, and it might even work in Safari, but who is using that anyway?
So this is a new form element. So let's run this. And this is a form element with a microphone. Wow, great. That's why the standard is only done in 2017. No, seriously. I should have a microphone somewhere here, so if I go like blah, blah, blah, then wow,
I have speech recognition in the browser. Now, of course, this sounds like a stupid feature, but of course it's really interesting if you have, for instance, mobile applications that want to have a kind of speech recognition and speech input. As you can see, X prefix. So it doesn't work in all browsers yet,
but still, I mean, it's a nice thing. But if you talk about new form elements in HTML5, what we usually are talking about is something like, let's say, input type equals, let's say, email. So we have a lot of semantic form elements, and the nice thing is, let me give this an idea as well,
if you have a look at the form field, I mean, that's the email field. It looks like a regular email field, but if I add some rubbish into it, and then later try to submit the form, where a button would be beneficial actually. So if I add a submit button,
and for good measure, also add a form around this. And if I've done that, and I enter some crap here and try to submit it, I get, please enter an email address. So I have built-in validation now.
So with HTML5, the one use case scenario of JavaScript is obsolete because we have validation built in. Now, of course, apart from those built-in features, and there's much more, there are features like, for instance, required field, range. So if you have worked in your past with ASP.NET web forms,
then most of the validation controls we had back then are kind of built into HTML5 now. But apart from all the markup, we also have a JavaScript API for that, so we can access that form field and have a look at its state.
So, for instance, if there's an invalid value in that form field, for instance, now there's an invalid value obviously because it's not an email address. We get the information, A, that the current value is invalid, and B, why is it invalid? Because, I mean, the format could be wrong or it could be a required field and there's nothing in the field,
so we get all of this information as well. So HTML turned from, you know, I just have fields and I don't care what these fields are for to a semantic platform saying, in that case, I have a field and that field is an email address. So I have the semantic information, oh, now we've got an email address in that field
and we can then also decide, well, the information in that field is correct or is incorrect. But, well, enough with the markup. I'd like to try out some of the more programming-oriented features and you see that in order to increase the risk a little bit of me failing, I'm using Webmatrix because IntelliSense is so awesome there.
So let's start with, or let's continue with geolocation. Out of curiosity, is anyone in this room playing a game called Ingress? Show of hands? One, one, okay. Very small hand. Are you blue or green?
Okay, we talk later. But, no, so Ingress is a game that was developed by a group within Google and this game, the whole purpose of that game is supposedly to amend the geolocation feature in Google Chrome.
Now, we'll have a look at that in a bit. First, let's have a look at the actual feature. So what geolocation does, I mean I briefly mentioned it, is we can kind of determine the position of the user.
Websites like Twitter and Facebook, for instance, do, or at least ask us if we want to do that. So let's write some code. Actually, that's one of the new features of HTML5. Type equals text slash JavaScript is default, so we do not need it. So we have the navigator JavaScript object.
That's where usually the user agent resides and some other stuff. And within that, we have now geolocation, and then we have three methods, and the method most commonly used is getCurrentPosition. Now, getCurrentPosition is an asynchronous call because determining the position might take some time.
And as you know from, for instance, AJAX requests, they also take some time, so they are done in an asynchronous fashion. So we send the request, fire and forget, and we have callbacks that inform us if we got a result or if we got an error. Now, I'm a very optimistic person, so I omit the error callback. All I do is the success callback. It should work.
So, result. Now, we get a result object just in case that we actually do get a position, and the result object has a couple of properties, and the most important property is chords, which gives us the coordinates. So let's say we have the latitude is results, chords, latitude.
There goes IntelliSense. And longitude equals results, chords, longitude. And what we can now do is whatever output is to the console, so console.log, latitude, blank, and longitude. All right. Actually, this looks good, and yeah.
Actually, let's try to run this. So geolocation is the name, right? So geolocation, and we maybe should start the console. And, wow, now we got some coordinates.
That went really quickly, actually. Now, I have a wired connection here. The organizers also kind of give me a wired connection just in case that the Wi-Fi is too crowded. Now, actually, let me just do one thing. Let me turn Wi-Fi on. So you see Wi-Fi is now on on my machine, and I run the same script again.
Note that Wi-Fi is on. However, I'm still using the wired connection. I'm not using the wireless connection. So let's go to the console. Oops, that's what I wanted. I want to paste it here. And, well, now we get a result, and you see that the results are a little bit different
because I turned the Wi-Fi on. Hmm, that's interesting. I mean, what changed by turning the Wi-Fi on? First of all, let's briefly talk about how this actually works.
Because, I mean, how can the browser somehow determine the current position? I mean, on many devices it's possible because my mobile phone has a GPS in it, right? So it could trigger GPS. On some operating systems there is a kind of GPS service running which you can hack into.
And, well, what basically happens here is that, in that case Google, since it's Google Chrome, Google has a location service. So the browser sends an encrypted request to the service and receives a potential position, if possible.
And if you're using IE or using Microsoft service, and there are other services too, although Firefox, for instance, is using Google service as well, and Opera does too, at least at the moment. Now, what does the service then do? Well, the service receives which kind of information?
OK, the IP address. So based on the IP address we might be able to assess where we are. Well, since it's hard wired and maybe the infrastructure here is from the spectrum organizers, it might be safe to say that maybe they can determine exactly that we are at least in Oslo spectrum, at least in Oslo,
maybe even in Oslo, quite central. But if Wi-Fi is on, I mean, let's have a look. I mean, technically we have Wi-Fi now. So we have a couple of Wi-Fi networks now. For instance, the spectrum network, five bars.
Ah, that's interesting. That's interesting information for the server. So the user is now in an area where the spectrum network is at five bars. So he must be exactly where the spectrum network is, which might be at Oslo spectrum. Who knows? So this kind of information is also taken into account.
Now I briefly mentioned the game Google is providing. And the game is, if I understand correctly, it's like geo-caching. So you run around and kind of look for stuff. And since the idea of the application is that the current position is always available to the application.
On the other hand, since most mobile phones have their Wi-Fi turned on, Google now knows, OK, exactly this position in Oslo, where you can only go on foot, these networks are available with these network strengths. So you can kind of try to triangulate the current position. And that's one of the reasons why the results here should be actually quite good.
Now, I did not try this before, so let's see how good that is. Let's go to Maps, Google, and O. And let's first try the coordinates we got from the wired connection. So we are here. Well, actually that's not too bad.
But, well, as you can see, so the spectrum is here, right? Here's the transition. OK, so it thinks we are here, which is good. Now let's have the one also wired connection, but with wireless turned on.
Well, we are on the spectrum, right? So this gives us really good results, and the opportunities we have with that feature are quite endless. I mean, location-based services is one of the key ideas of many, many services
and companies at the moment. And you can now plug into them. Now, what you did not see here is, because that's the way I configured my browser, usually the browser of course asks you, may I determine the current position? And I kind of once said, OK, allow for all times.
So users still have to agree that the position is being determined, right? But from the API point of view, this is really, really neat. On mobile devices, you've got more information than if the GPS gives it to you. So you get stuff like the altitude, the heading, the speed, something like that.
So really, really nice thing with a very simple JavaScript API. So no more form validation. We can now do, well, real programming. OK, so this is one of the things we like to use quite a bit. So many of our customers, for instance, have store locators, which try to find out where your nearest store is.
And well, by determining the position, it's just easier to determine the nearest store without the user having to enter a city or postal code or address or something like that. OK, so that's the geolocation feature. Actually, I'll be more than happy to zip up the code we are just creating and email them to you or put them online just in case.
So it's probably easier than just typing this all in itself. OK, so that's the geolocation. Of course, there are many, many more features, and one I'd like to pick from that list and more discuss and share with us, because there are some advantages and disadvantages, is online and offline scenarios.
Now, you've heard that the new Xbox is kind of always on, so you need to have an internet connection for many of the use scenarios, which kind of led to people now flocking to the new PlayStation, as far as I've heard. It's also cheaper. Because, well, of course, we are online most of the time,
and probably half of the room is also in kind of a way online with their mobile phones or laptops or whatever, not. But, of course, you might be in a train, in a tunnel, on a plane someplace where, well, you are not online,
or the network here might be too crowded and you are, well, technically online, but effectively offline. And three new features in HTML5 or around HTML5 that support online and offline scenarios. One of those features, and there's been a session on that, so I don't want to demonstrate this specific bit,
but just want to give you my stance on that. One of the features is called local storage or web storage or DOM storage. So even the specification kind of mixes up those names. And the idea is that you store data locally, like you do with cookies. Cookies are stored locally as well, but you do not send this data to the server with every request.
You just store it locally, and that's a JavaScript API that allows you to store session data until the browser is closed or to store it permanently. So you can store data locally, and one of the... Oh, no, actually, a lot of web applications are doing it. They are, for instance, storing information,
so calendar applications store calendar data in order to load less data. Some companies or some websites store images or big logos locally so that they do not have to be transferred over and over again from the server. So this is actually a very nice API in order to use it.
It's quite simple to use. It's more or less a hashtag. However, there's a bit more to it. What we also have now is the application cache, which was also demonstrated in one of the other talks. So the application cache is something like the browser cache, but you know how the browser cache works.
It's us as developers asking the browser via HTTP headers, oh, you could cache that if you're in the mood, dear browser, please, if you would be so kind. And usually the browser doesn't give a thing about this. So that's the browser cache, right?
So we ask the browser, but we don't know if it works. Usually it doesn't. And if it does, we do not want it. But no, really. And what the application cache is, we instruct the browser to store specific data locally for offline use, which means if we are offline,
then if the resource we want is in the application cache and it has been properly configured, the application can still load. So for instance, for my private appointments and schedule, I'm using Google Calendar, and there is an offline version of Google Calendar. So when I'm, let's say, in a tunnel
and try to have a look at my appointments, I just load up the offline version of Google Calendar and I see from the last time I synced all my appointments in the browser setting. Because it's using the application cache and it's using local storage in order to store my appointments
from the last sync. So this is really nice. And there's one more ingredient, and I'd briefly like to discuss this ingredient because it sounds like the simplest scenario and simplest thing on our to-do list, but actually it's the hardest thing. It's the, whatever I called in the last two minutes, when we are offline.
I mean it sounds simple, right? When we are online, then we're offline. Well, kind of. There is an API. And actually that API, we don't have to write a full program, but Len just writes in here, there is, again, Navigator, online, with a capital L,
which kind of is weird, but it's for backwards compatibility with some browsers that implemented earlier than others. So navigator.online is a boolean value that tells us if we are online or not, according to the spec. Well, let me tell you what this value actually does.
There are two things. If navigator.online is false, then we can be quite certain that we are offline. If navigator.online is true, then there is a chance that we are online, right?
No, seriously. So, for instance, I mean, let's just imagine, I wouldn't have the Wi-Fi connection, I would have the Wi-Fi connection. So if I turned Wi-Fi off, on Windows 8, immediately the value of navigator.online would turn to false. On Windows 7, it does not.
Well, not in all cases. Plugging, replugging the core tier would have the effect that navigator.online switches from true to false or from false to true. It also works quite well on a Mac. However, you can never be certain. And on the other hand, I mean, that's the really bad thing about this.
What does it mean we are online? So imagine. I mean, I think there were these 15 minutes two days ago when the conference network was really, really bad, right? Well, my computer showed Wi-Fi five bars.
So I was online, technically. But did DNS resolution work? Could I do anything? Could I load any web resource? Not at all. So, effectively, I was offline. Although navigator.online correctly said I'm online. It gets even harder when you're doing local testing. Because even if you're offline, accessing local host should always work.
So what you would usually then try is that you use a service like localhost.me which kind of gives you a URL that then in turn maps to a local host which might make it a bit easier. So that is the biggest challenge to overcome for offline scenarios.
Determining if you're online or offline. I mean, the standard way of doing that and actually really determining if you're online is sending an AJAX request to the target server. We have to take some things into account here as well. So if you send the request, you have to disable caching because if the request was successful 10 minutes ago, that just means that 10 minutes ago we were online.
But we are not online right now, at least not definitely. So you usually do whatever a post request, send the appropriate headers. You might also do some crazy things with the URL to make it unique, but I think this kind of defeats the purpose of URIs.
So that's not the recommended practice. At least we are not really happy with that, so we try a mixture of the other techniques I mentioned. But basically this is what on and offline scenarios give us. And this makes it really, really appealing to write applications that work offline as well, especially if you have a mobile client, which tends to be more offline than other clients.
And if you were at yesterday evening's phone gap session, for instance, you saw some really interesting information on how to architect your phone gap apps in order to have an HTML5-based app that then is turned into native apps on iOS, on Android, and other operating systems.
And well, also these apps need to be somehow offline aware, or at least they should be. And with HTML5 you have the mechanisms, you have the means to do that. So I can just recommend that. Alright, let's try something else. And I'd like to talk a bit about communication, so let's do this.
As you know, you can do more and more things with JavaScript. And that means that JavaScript code gets, of course, more complicated and, well, takes a bit more time to run it. If you're as old as me, then you know that in former days
the browser was like 98% idle and the web server was 98% busy and with our new JavaScript-based applications this kind of turns around. So sometimes the browser is really, really busy. Well, let's just create a very, very busy browser. So let's just do some really complex finance calculations.
For the sake of time, I won't do any complex finance calculations. I'll do some rubbish calculations. But of course they serve as a metaphor for the really complicated calculations. So let's just add up some numbers. 4 var whatever, j equals 0, j...
I don't know, how many? 8 cores? Oh, 8 cores, 8 zeros. That sounds like a plan. And var r equals math random. So I draw a random number and add the square of that number to i.
Makes absolute sense, right? Finally, let's say console log i or alert i. I'm not sure if he's seeing that anyway.
So let's use a browser that's not so fast. Do I have someone here? Okay. It's important for the sake of demonstration. So, not geolocation, instead worker HTML. So now it's doing the calculations and somehow I don't know my machine.
Oh, calculations are already finished. Well, that was not what I planned, actually. Let's make them even more complex. Twice the fun. Well, you see now I'm clicking here and nothing's happening. And with some luck, you get this non-responding. So the usability and the user experience is really bad.
I mean, if you bump this up even more, eventually we get this dreaded message hopefully none of you has ever seen. It's this long-running script. Oh, it's not long-running enough. Okay, give me one more try, sorry, otherwise I'll proceed. This is the first time in this talk and the only time in this talk where I want to see an error message.
And that's the only demo that failed, right? All right, so eventually you might get this message, a long-running script. Yeah, that's the one. Have you seen that before? Okay, on your own sites or did you kind of do serve for specific information? Uh-huh, okay, okay, good, I believe you.
And, yeah, so, well, it's kind of embarrassing. And of course, even without that error message, the slow-responding browser, and in the case of Firefox, also killing all the other browser tabs effectively because you cannot switch really well, is something that should be avoided. And, well, I can say continue and then may, well, it tries to continue
and eventually there might be a result or yet another error message. But what we can do now is if you have this kind of complex calculations or complex code, we can put the code in a kind of background thread. I mean, the threading model in browser is much more complicated than the way I'm describing it now.
But it can be compared to the Silverlight model if you're used to that. So we have the foreground thread which takes care of drawing the UI. So if that thread is blocked, then, well, you might run into issues. So you can defer code execution to a kind of a background thread,
and that background thread then doesn't have any access to the UI because it's running separately from the code responsible for drawing the UI, but it also does not block the UI. And actually refactoring here is pretty easy. I will create a new file, and this time I'm creating a JavaScript file.
Well, let's say I call this worker.js, and I will use the worst code pattern ever invented. I will use copy-paste, and, well, I just copy the code here. Now, this code now resides in a JavaScript file.
What I want to do is I would kind of call this JavaScript file and communicate with the file. As I mentioned, the JavaScript code doesn't have access to the UI. However, there is a communication mechanism that allows us to communicate with the JavaScript file and vice versa. And this is how it's done.
So what I'm doing is I'm using another script block, and then I create a so-called web worker, or in short, worker. And as an argument for the constructor, I'm using the name of the file, so worker.js. Now, this loads the JavaScript file and kind of runs it in the background.
All right, so what would happen now is the file is loaded in the background, and then, well, it does all these fancy calculations. We can try this out. So we reload, and you see the browser is still reacting. But of course, my calculations, they are done in the background,
but probably you won't believe me because you do not see the results. Trust me, they run in the background. But probably I should show you that they really run in the background. Now, I can communicate with the web worker, so I can send a message to the web worker. The method is aptly called postMessage, and I can't send any message.
Let's say, start. So this sends the start message to the web worker. I could call it stop. I could call it no matter what. It doesn't matter. It's just a string, which I'm sending to a worker. Now, in the worker, I have event handling,
and there is a message event that's triggered whenever a message is sent to the worker. So I could say self.onMessage and set up an event handler, and this event information here now contains the message. So what I could do now in the code is have a look at the message
and see, OK, if the message is start, do this. If the message is stop, do that. If the message is status, do that. So I could even have kind of like a progress bar how far my calculation is. Well, for the sake of time, I just do it quite trivial here, and whatever message I'm sending, I'm just doing my calculations.
And at the end, I have a result. But what do I do with the result? I would like to send it back to the HTML file, to the callee. How do I do this? There is a method, and it's called, you will be surprised, postMessage. So I'm just posting the message back, so I'm just taking the i, that's my sum here,
and posting it back to the callee. Now, of course, now the caller also has message handling, so if for the caller the message event is fired, then, well, we handle it. So, for instance, we just have a look at the event information we receive.
To sum it up, we instantiate a worker JavaScript file. We send it a message. Once the JavaScript file receives the message, it does some nasty calculations. After the calculations are done, the result is sent back to the callee. The callee is happily waiting for the message without blocking the UI,
and then processing that message. Now, let's turn the console on and run this. And as you can see, it's doing the calculations. And they take some time.
And they still take some time. So I would say, we come back to that after the next demo or so, and see if and what the result here is. But it's now really doing the calculations in the background. And as you see, the UI is not blocking. Oh, there we are. So we get a worker message event.
And, well, among other things, it contains the sum and a type, the target and some other information as well. So now that the calculations have blocked the browser for half a minute before, including the nasty error message, and now did the same calculations in the background without blocking the UI.
All right. The API you are seeing here, postMessage method, message event, is an API that is available in many, many scenarios and use cases now in a browser setting. For instance, you can talk between different browser tabs
using more or less the same API. It's a very, very little known feature in JavaScript. Well, that actually doesn't have that much to do with HTML5. Well, a little bit, but it's a very unused feature, but it's great if you have your application open several tabs to synchronize those tabs, because you can, well, talk between each other.
And some of the more advanced communication APIs, they also use, well, a kind of mechanism like that. So how are we doing on time? Oh, still good. Okay. So let's do something else, and it has to do with communication.
I mean, there are so many buzzwords at this conference, and, well, usually, I think buzzwords suck, but the content here, of course, is really, really great, and I hope you enjoyed the conference as much as I did. And what I'd like to do now is to turn it up even more
and use the ultra-buzzword that we could possibly have. I'm going to use Node.js. Now, Node.js, of course, is also JavaScript, but Node.js has nothing to do with HTML5. However, what you can do with Node.js, and that's another kind of hype at the moment, which, well, is its own specification, is WebSockets.
Now, WebSockets is one of the many new communication mechanisms, and there are many more. WebSockets is just the one that's mentioned very, very often. But WebSockets' specification gives us a real-time communication mechanism
using full duplex in a bi-directional way. So a lot of technical terms that were not available before and are really, really useful, especially for real-time information, I mean, the standard example which you usually get is having a chat. But, well, a chat is something that kind of Facebook solved
and Google solved, and these are the only companies that use it in their products, more or less. But apart from that, just for displaying real-time data, like stock information or news or finance information, this real-time approach to data is, in my opinion,
one of the key features. Alright, so let's try to whip up a server real quick, and I'm using Node.js, again, because it's JavaScript and because it can be done quite quickly. So, first of all, I need an HTTP server as the transport server, so to speak. So I'm loading the HTTP module,
and now I have an HTTP server available, which I will use later on. Then I need a WebSocket server, so let's call it WebSocketServer. And there is an extension, and I did install the extension previously because it takes some time and requires downloading, so I'm a coward, so I wanted to have it available to be independent of the server connection.
And well, then I create a WebSocket server, and what I'm basically doing is I create an HTTP server first, and you see I even got IntelliSense here within WebMatrix for Node.js, which is actually kind of nice. And well, as an argument, I could do
an event handler that handles request and response. Actually, if you forgive me, I won't do anything if I get a regular HTTP request to the server because we don't need this. The only thing I need is the server itself, and then I listen to an arbitrary port, let's say, whatever, one, two, three, four. And well, if I listen to the port,
then I can also have an event handler, but I'll let that empty as well. So I have an HTTP server which is called S. So far so good, but it hopefully gets better because I need the WebSocket server. And the WebSocket server, I mean, I already loaded the module I need, so I just do a new WSS, new WebSocket server.
And as an argument, I have to provide which HTTP server am I using as the transport, and in my case, that's S, the server I just created, okay? So I create a new WebSocket server, and as an HTTP server, I'm using S, the HTTP server I just created.
And now I have event handling, and the event handling here looks exactly, well, more or less, as the event handling JQ is using since version 1.7, so I'm having the on method and then just provide the event, for instance, in that case, the request event. So once a request comes in to the server, I have an event handler,
and the event handler receives the request. And well, the first thing I have to do, and I tend to forget this, so I try really hard not to forget this, this time, when you get such a request, you have to accept the request, right? Because by default, the requests are denied,
which kind of make sense, so let's create a connection, and I create a connection by going to the request and accept the request. And in order to accept the request, I have to provide some arguments. If I want any metadata, where the request is coming from, the region, so for the sake of time,
just use the default values, which basically accepts any request, no matter where the request is coming from. And now I have a connection, and when the connection receives a message, so we once again have a message event, then I can handle this.
So I got an event handler, and the event handler has a message as an argument, and well, what I could do is take the message, maybe I should use UTF-8, I think that's safer, so a message UTF-8 data. So I take the UTF-8 data of the message,
and well, then I can kind of process the message and can send something back. So I can send anything back. I do this by using the connection again, and then send UTF and, well, actually I could send the message back. So I'm just echoing, echoing the data coming in. That's a WebSocket server.
Create the HTTP server, load the WebSocket module, instantiate the HTTP server on port 1234, create a WebSocket server that is using the HTTP server as a transport, once a request comes in, accept the request. Once a message comes in, send the identical stuff back.
Now, let's try this out. So node server.js. Alright, it gives me a warning because I don't have Python installed on that demo machine, and without Python, nodes XOR and UTF-8 code is sub-optimal,
but I hope it will work without XOR today. And now the server is technically running, now all we need is a client calling that. And in order to do so, we just create another HTML element,
and that HTML element then essentially can connect to the WebSocket server and exchange data. So I'm once again creating a script element, and then I create to the WebSocket. So we have WebSocket, and then we provide the name of the server, and the protocol now is not HTTP,
it's WebSocket, WS. And then, well, let's take the IP for good measure, and 1234 I believe was the port, and now we have the WebSocket, and once we have opened the connection to the WebSocket server, then we can have an event handler,
and in the event handler, we just call to the WebSocket server, and then, for instance, send some data. I'm just using a random number here, I hope you can forgive me. And once we receive a message back from the server,
well, we can have a look at the message, so let's do so, just console log E. And the thing is that establishing the connection, sending data, and receiving data is decoupled. Think about AJAX. If you do AJAX, you do a call, and then you have an event handler that tells you when you get data back for that specific call.
Here we have an event message, so whenever you get a message from the server, this event handler is executed. That means we have push. We don't have pull anymore, we essentially have push. If it works, let's see. So, how do I call this guy, WebSocket?
Turn on the console. All right. And, wow, we got a message back right away. And, well, the message gives us the origin, so the name of the WebSocket server, and it also gives us the data we sent. So we sent a random number there,
and we got the random number back. Of course, that's nothing special, but still, you see it works really, really well. It's also very, very fast because there's not so much protocol overhead than in the regular pull mechanism we got on the web, together with some of the other communication APIs in HTML5.
I think this is one of my personal highlights. All right. So, let's... Well, do I have enough time for a rant? Oh, I do have. OK, so that's what we'll do as the next and probably last topic today. I would like to talk about drag and drop.
OK? Who has ever implemented a kind of drag and drop in... in Silverlight, for instance? OK, did you like it? It was a lot of work. Very, very good. Well, that's not very, very good, but I feel your pain. I tried it too. So has anyone ever tried implementing drag and drop manually?
It's not like using jQuery UI and writing three lines of code. That's not working, right? Has anyone tried doing drag and drop in JavaScript manually? Did you like it? OK, you don't look very happy. OK. And, oh yeah, it's a pain, because what you have to do in Silverlight and what we have to do in old JavaScript
is more or less having a... we build our own state machine. Right? So we have an element. When we click on the element, we go, state machine, into drag mode. Once we release the mouse button, we are out of drag mode. When we move the mouse, if we are in drag mode, we are moving the element. If we are not in drag mode, we do nothing.
And now we have drag and drop in HTML5. With an API based on Internet Explorer 5. I kid you not. Internet Explorer 5. Do I need to tell you more what I think of this API?
Let me put it this way. If you do drag and drop with HTML5, it would even run in IE6. Oh well. Oh, it's horrible. I mean, I don't know. No, I won't fall deep enough, actually.
No, but seriously, it's horrific. Horrific. But well, drag and drop in some cases is actually quite useful. Especially when combined with another API, another set of APIs that we now have, the file APIs.
Yes, file access. So if I'm wearing my security hat, whenever I think about HTML5, I got to cry a little because, I mean, having cross-domain HTTP requests, oh, security point of view, it gives me shivers. Having file access locally, oh, gives me shivers as well.
Actually, there is this protection built in, and then actually we did some pretty nice things with these APIs. But still, they are a real, real, real pain. However, since unfortunately we still got 10 minutes, I will show you that, if you don't mind. So let's have a look at how drag and drop works and how the file APIs work.
So let's do this. I created a new file, and I called it whatever. DND, drag and drop. And in that file, I would like to have a drop target, so someplace I could drop something into.
I mean, I suck at HTML and CSS. So the company at home, probably our HTML and CSS specialists, they are probably watching the stream and cracking themselves up. But, well, sorry guys, I can't do better. So I call this drop.
And in order that we see it, I style it. Now here comes my CSS magic. I could do a class, but let's just do whatever. With 300 pixels height, 200 pixels border, 1 pixel solid black, background color orange.
Wow, I'm awesome. And then I also would like to have, let's say, let's use a select list. So the idea is, I drop stuff into the div, I handle the associated events, and then I display information about what I dropped in the selection list.
So that's the scenario I'm about to build. So let's do this real quick. So first of all, we have to wait until the page has been fully loaded. So I'm using window.onLoad. I could use a lot of function jQuery as well. Now, once I've done this, I access the drop elements. So var d equals document get element by id of drop.
And now I have to set up the events. And there are several events, drag and drop events. And that's the only thing actually that IE5 gives us. And I have to write event handlers for those events. And the three events I want to do is drag enter,
which is kind of mouse enter while dragging. We have drag over, so we have already entered and we're still moving our mouse over while dragging. So the state machine is built for us, but that's all. And we have drop, so I release it. And so I do add events listener.
And for drag enter, I just want the browser to stop what it would usually do. So let's just call this stop. I'll implement this later. And I do the same thing for drag over.
So I want it to stop. And well, finally what I do is I have the drop events. So I let stuff drop and let's say handle. Okay, so these are the event handlers and now I just have to write the code for those.
So I have to stop event handler twice here. So let's write this event handler first. And what I want to do is usually if I take a file and drag it on a browser, the browser tries to open that file. This is not what I want in that case because I want to handle the file I'm dropping. So I have to ask the browser or to instruct the browser to stop what it's doing.
So first of all, I tell the browser to stop propagating the event further up because we have event bubbling. And I also tell the browser to prevent default behavior. Prevent default means don't do what you usually do when the event happens.
So in that case, for instance, do not try to open the files, just drop it. So we stop propagation and we prevent default. Now let's go to the really interesting function, handling the event. Drag and drop is a topic of its own and it's actually quite complicated,
especially how you access data and how you can exchange data between entities on an HTML page. But the basic principle or mechanism is called data transfer. So we have a data transfer property which gives us access to the data being transferred.
Now let's go to e.datatransfer.files because that gives us a kind of list of those files I have been dropping on my drop area.
So when we drop something, some files, I can access these files like this and then I can iterate over those files. So i0, i smaller than files, the length, i++. And in that case, var file equals files of i. Now file is not the file itself.
We would need to use another class in order to access file information, for instance, so what's in the file. However, what we can access using that file list is file metadata. So we can have metadata equals file.name
and we got file.type, that's the MIME type according to the local system. And then file.size, I think, is also possible. Alright, so I can access file.name, file.type, file.size
and then I can do whatever, a new option with the metadata information and add this option, document get elements by id of list, you remember the selection list, add the option to the list. So I drop some files in the div and then I access the file
or the files, iterate over them and add them or the metadata to the selection list. At least that's the plan. So let's see, drag and drop. Oh, something. So what I messed up is the CSS, oh yeah.
Is height really not possible? Thank you very much. Oh, now it's working, okay. Thank you very much. So I do program, I cannot speak English.
Okay, excellent. So here's the drag and drop area, so let's see, do we have... Actually I have the PowerPoint slides for today. So it says move. I add it in here and you see that the metadata has been added to the list.
You also saw that the download arrow came up. Why did the download arrow came up? Well, because what happens after dropping, what do I need to do? I need to stop it from doing the default things and that's why we need the stop function, okay? So I drop files, I get information about those files,
and you may have seen this effect a couple of times in the web. Modern file upload things, like if you're working on a photo book, you were dropping files in the browser and then you saw small previews of those files and their file size. This was basically this technique plus a way to read in those files
and then kind of display the files' content as images. So you get really, really modern-looking UIs. I mean, of course, this is convenient. It also might open some text surfaces because maybe some hackers now prompt users to drag some files into the browser and then they are able to read the contents.
But still, I mean, I think it's ultra-convenient. And you see, it was not as bad as it looked. But still, especially if you drag from one area of the page to another area,
getting the data transfer right, it's a bit cumbersome. So if you're not working with files, maybe just using a framework like jQuery UI or some of the other UI frameworks is a bit easier. But combined with File API, you get really, really, really powerful scenarios which you can now do with JavaScript if you're willing to work with an IE5 API.
Well, we saw a bit of HTML5 form elements, geolocation, online-offline web worker as a part of communication. We managed to do drag and drop as well. And it showed a couple of other things too. This, again, was just my way of giving some ideas what JavaScript can really be used for.
What I've been showing you is something we actually have used in real-world applications for our customers. So at least in many scenarios, the technology is ready and the results are very, very rewarding.
And I'd be more than happy to talk to you more about this either via email or in the hallway track right after this session. Apart from that, once again, thanks for showing up so early. Enjoy your last day of the conference. Safe travels back home, and hope to see you at the London show in December next year. Thank you very much.