I realize a JavaScript library like jQuery that is specific to the HTML / DOM wouldn't work nor make sense in a Flash ActionScript application. But what about other JavaScript libraries? I was reading that ActionScript is a superset of JavaScript / ECMAScript which is what got me wondering.
If it wouldn't use JavaScript libraries "out of the box" could a JavaScript library be adapted relatively easily? Also, does ActionScript support XMLHttpRequest or have a rough equivalent?
The syntax is similar, so you may be able to compile some code snippets. JavaScript looks more like the old Actionscript 2 though.
It's not only jQuery, but most JavaScript libraries are used to interact with the user interface or doing some communication things in the background. If they weren't, you could probably replace them with a server side library for the same job.
Many APIs, like the ones used for input and output are very different. If you are thinking of a copy&paste approach to convert a library, you would need to recreate a lot of those APIs for it to work. For example, a library to draw something on a canvas: You would either need to recreate the canvas API to draw the canvas instructions in flash - or create a wrapper to make flash call the original API to draw it on a real canvas. Alternatively rewrite all those parts, which are likely to found almost everywhere in the library.
That leaves us with libraries that strictly use non-js specific stuff. Maybe encoding/decoding libraries or algorithm and math heavy libraries. Those libraries may can be converted more easily. It would be quite a lot of work to refactor them into maintainable code though (in the OOP based Actionscript 3 sense). Apart from some less changes in the syntax, it probably requires almost the same amount of work to port the library to any other language. Also, chances are, that those generic libraries already exist for Actionscript.
This is a very old question but I thought to give an up to date answer.
Adobe ceased updates to its flash browser plugin as of January 12, 2021.
There are now some libraries and/or browser plugins being developed to continue flash support.
One that has the option of loading a JavaScript library from a HTML script src tag is Ruffle. As of this date it support 70% ActionScript-1/2 and 5% ActionScript-3.
The developers claim they plan for full support of AS1, AS2 & AS3.
I have tested it myself and found it to work quite well for many SWF files containing AS-1/2. The only thing required is to adjust your server software (ie. Apache, IIS, etc.) to allow wasm file support.
Use the link titled "Self Hosted" to download the necessary files that you must host.
ref. https://ruffle.rs/#releases
Related
I would like to implement client-side hyphenation via JavaScript on some large texts on my site. (I know about CSS3 hyphenation and will use it instead when available, but it's usually not available.)
I have been using Hyphenator.js, and it works well but is very large (my optimized, compiled build with just English comes out to 106 KB) and pretty slow. It's large and slow enough that I'm considering dropping hyphenation altogether. It's just a luxury anyway.
But recently I came across what seems to be an alternative: Hypher. What baffles me is how Hypher can me so much smaller and do the same thing. I'm wondering if anybody can explain this.
Does Hypher work just as well? Is there any reason to use Hyphenator.js instead? Hypher's readme has a link to Hyphenator.js at the bottom of the page, but none of the text explains the connection between these projects.
Does anybody have an opinion about the most efficient client-side hyphenation?
I had a look at hyphenation in JavaScript and found the following four libraries:
hy-phen: Is a pure JavaScript library developed by Yevhen Tiurin since 2016 using the MIT license. You are offered a JavaScript function that you can call to hyphenate strings. You only need to include the main JavaScript file and the desired language file to use it.
Hypher: Is a pure JavaScript library developed by Bram Stein since 2011 using the "Three Clause BSD" license. You are offered two JavaScript methods that you can call to hyphenate strings. It can only be installed using Node.js or jQuery.
Hyphenator.js: Is a JavaScript/HTML implementation developed by Mathias Nater since 2008 using the MIT license. The project is discontinued since 2018. It is not so simple to include into your project - you need to use the Merge&Pack tool first to create a JavaScript file that you can then include. It automatically scans the HTML page and adds hyphenation to selected HTML elements. There is no JavaScript function that you can call to manually hyphenate strings.
Hyphenopoly.js: Is the follow-up project of Hyphenator.js and developed since 2016 by Mathias Nater using the MIT license. It dropped some features of Hyphenator.js and is a bit simpler to use. Nevertheless it works the same way meaning there is no JavaScript function that you can call to manually hyphenate strings.
All four libraries are using the hyphenation algorithm developed by Franklin M. Liang that uses matching patterns to find hyphenation points in words. This algorithm does not provide 100% correct hyphenations as stated by Liang in his thesis:
These patterns find 89% of the hyphens in a pocket dictionary word list, with essentially no error.
The primary reason Hypher's so small, comparatively, is that it relies on an externally-loaded jQuery for page integration. Hyphenator.js is completely standalone and thus has to include way more boilerplate for manipulating HTML across browsers. (They even re-implement some jQuery functionality.)
To be fair, Hyphenator.js is a relatively old project that hasn't been completely rewritten along the way to take advantage of substantial browser improvements. (Note that they proudly support Firefox 3.0.) And, more charitably, Hyphenator.js has many more finely-grained settings.
If you're already using jQuery, and don't use Hyphenator.js's advanced API, switching to Hypher may be a worthwhile improvement.
I have developed one of my modules using Dojo. Its gone really well and I have done a lot of custom plugins and server support in Dojo to allow AJAX calls, RPC + SMD communication with my server.
However, now that I am getting onto the user side of things, I am seeing that jQuery has some really nice already built plugins. Do you think it is possible to support both JS libraries realistically without it being a massive problem?
What kind of integration can I achieve? Does anyone have experience in this?
I have probably written somewhere in the region of 30k lines in Dojo for my Administration panel...
jQuery is very good about not messing with the prototypes of built in javascript objects (unlike Prototype), this allows it to be used with other libraries quite easily.
A source of potential conflict is jQuery's use of $ as a shortcut for jQuery. I'm not a dojo user, but if this conflicts with dojo in some way, there are instructions addressing this.
That said, I think you'd be better off looking at these jquery plugins and rewriting them and porting them to dojo. I'm sure the dojo community would appreciate it, and it would give you experience. It'd also make your application a little slimmer in the waist area.
Edit: I've noticed a couple answers trivializing the download speed of adding an additional library. I'd take this with a grain of salt.
As developers we tend to see only the extra 10ms it takes to download the library over localhost, or from our development server on a 100 Mbit LAN. The download speed is not so trivial from California to Virginia, or especially from USA to Europe. Additionally, it adds further burden on your client's javascript engine. If they are using a 1-2 year old good computer with Safari or Chrome, this would be negligible, but if they're on IE, FF2, or some versions of FF3 the difference can be severe, or at least measurable.
When using 2 libraries (both of which, I'm sure - were designed to be used by themselves) you have 2 main worries:
That one library will effect the other.
That having a dependency on 2 libraries will bloat your pages.
In this case, I would bet that #1 is not going to happen. Although #2 is still a concern.
Most of the popular JS libraries can be scoped to their own global shortcuts. JQuery can be set to not initialize the $ variable. JQuery aside, I hear that Dojo and Prototype can work together without conflicting.
Regardless of what combination of JS libraries you decide to use, the best way to get information on compatibility issues is to hit the mailing lists relevant to the JS libs you'll be using with each other.
http://docs.jquery.com/Using_jQuery_with_Other_Libraries
http://www.dev411.com/blog/2006/06/13/dojo-and-prototype-together
Query.noConflict() makes for fairly easy interoperability because you can redefine $. As hobodave draws attention to, Prototype is lousy in this regard (because you can't easily just redefine $ with Prototype). I am not sure but I think Dojo doesn't have any issues of it's own and plays nicely with others out of the box (please someone correct me if that's not true).
The biggest problem I've had is the number of "must have" libraries written in specific frameworks, such as for things like sophisticated graphing that would be non-trivial to implement from scratch.
Bloat is bad, but compared to image sizes JS script sizes are of negligible concern (because it's so small and connections are so fast and it's only on first page load if you get your caching right, it's almost a non issue). I'd say maintiainablity being more of a worry, and it's a matter of deciding if you want that must-have-plugin that you don't have the time or inclination to reinvent in whatever framework you are using.
I have used Prototype, jQuery, and ExtJS on several projects (for various reasons) and almost always use jQuery and ExtJS together. One way to limit trouble would be to avoid mixing libraries in any given page - keep Admin page to dojo and new pages to jQuery - but what fun would that be? :-)
I find few problems when integrating jQuery and ExtJS. I pick a framework for classes/objects/inheritance (I use ExtJS) and stick to it. Then, I use ExtJS to create most widgets and I use jQuery for low-level DOM manipulation and simple widgets. Again, I cannot recall running into conflicts when using two libraries, but FireBug is a good tool to uncover suspected causes of such conflicts.
I'm involved in writing a Flex/ActionScript library and in the future I will be involved in writing the same library in JavaScript. Rather than writing a library in each language and having to maintain them separately I was wondering if it was possible to:
1) Write the code in one language and share the code into the other e.g. Write the code in JavaScript and use the same .js files in ActionScript
or
2) Write the code in one language and perform a conversion into the other
I know it's possible to communicate between Flash/ActionScript and JavaScript but I'd like to avoid the overheads in using the technology bridge so this isn't really an option.
How do other people deal with writing and maintaining libraries that do exactly the same thing but in different languages? Specifically how do people do this between JavaScript and ActionScript?
How about Haxe.
You write the code in one language and they can compile it into various forms, including JavaScript files and compiled flash (versions 6-10). They even recently started supporting C++ compilation.
This would allow you to have the same source code (pre-compilation) for both your JS and AS3 projects.
(Noticed it when FlashDevelop started supporting it)
PureMVC does this quite well. The reference implementation is written in AS3, and the ports (including the JS version) are maintained based off this implementation. It would be non-trivial to write a converter, and it would likely be simpler to maintain the separate versions.
Given a set of Java source code files, how can I compile them into one or more JavaScript files that can be used with hand-crafted JavaScript?
GWT is one option, but every example I've seen so far is aimed at building fancy websites. The simple use case of just converting Java source to Javascript that can be used together with handcrafted JavaScript hasn't been well-documented.
I started a thread on the GWT mailing list on this subject, but opinions seem to be mixed on whether this is even feasible.
One person gave a very useful tip, which was to check out GWT-Exporter. The problem is that neither source code nor documentation is readily available, although there's this and this.
edit: GWT-Exporter source code is here
I've also seen Java2Script. But again, I wasn't able to find examples of how to solve my simple use case.
What's the best approach to this problem? Is there something better I'm missing?
When you use GWT, you're basically converting the UI portion into Javascript (and it assumes that you use the UI widgets provided when you write your Java). Only some of the Java libraries are accessible within Javascript. Typically in a GWT application anything that makes heavy use of Java libraries would run on the server side and connect to the Javascript as AJAX (which GWT handles for you). So GWT isn't necessarily converting your full application into Javascript (though it can if you're willing to limit your use of Java libraries and some functionality).
At any rate, if this approach (calling out to Java running on a server from within Javascript) appeals to you, one nice option is DWR, which basically allows your Javascript to directly call methods in Java classes running on the server (without you having to build a web service or other frontend). Not what you asked, I know.
More relevantly, it looks like there's source code for a sample app demonstrating the use of gwt-exporter.
I am not sure if it fits your use case, but if you agree to drop Java APIs and use JavaScript APIs from Java, then you can use JSweet, a Java to JavaScript transpiler built on the top of TypeScript. It gives you access to hundreds of well-typed JavaScript APIs (DOM, jQuery, underscore, angularjs, etc). It generates JavaScript code and you can mix it with legacy JavaScript and TypeScript code.
Note: JSweet will not work for legacy Java code and legacy Java APIs, but your use case did not mention reusing legacy code.
[UPDATE] Since version 1.1, JSweet now also supports some Java APIs such as Collections (java.util). So, it is possible to reuse legacy Java code to a certain extent. It is also quite straightforward to add your own support for Java APIs.
While the question is about compiling Java sources to JavaScript I think it's worth mentioning that there is TeaVM which compiles Java bytecode to JavaScript. I have never tried it, but it seems very promising.
Given a set of Java source code files, how can I compile them into one or more JavaScript files that can be used with hand-crafted JavaScript?
Although there are many solutions to convert Java applications to Javascript, you are interested on a solution where new javascript code may interact with the resulting code. This is an update (as 2018) of the other answers.
There are different types of tools. For instance, you may find tools that allow you (1) convert java code to javascript; (2) convert bytecode to javascript, asm.js or webassembly; (3) execute java applications directly in the browser and (4) create solutions that combine java and javascript. You must select the solution to use depending on your requirements.
Converting Java source code to Javascript
Some solutions take java source code and produce a javascript equivalent version. Usually, these solutions transforms the Java to Javascript, but do not support all the behaviours and libraries of the Java runtime. The resulting code may not support some java standard libraries. Typically, they are used to create HTML application using Java but not for migrating the code. Pros: The resulting solution may include very small files. You can use it to reuse your own business logic classes without considering GUI or platform specific libraries. Cons: it is possible that you cannot use some functionalities of the Java platform. It requires access to the source code.
JSweet converts Java to javascript. It includes API bindings for 1000+ javascript libraries. You can write java code that use these libraries.
It converts java to typescript and later uses the typescript compiler to create the corresponding javascript.
It can produce multiple types of javascript modules and typescript definitions. You can use the resulting code in javascript very easily.
j2s, is the compiler used by the Eclipse RAP platform to translate java code to javascript. It is used there to convert the SWT (GUI) widgets to javascript and HTML. It does not support all the Java standard libraries
It may convert simple Java classes to be used in javascript. You must use the classes considering the OO Java-Javascript simulation performed by j2s.
Converting Javascript bytecode to javascript
These solutions take compiled java code (.class files) and produces equivalent code in javascript, asm.js or webassembly. Considering that the java code may depend on java standard libraries (i.e., the JRE), these solutions typically includes ported and pre-compiled libraries. Pros: you do not need to change anything in your code. You do not need the source code neither. Cons: the resulting solution may require the load of a lot of files.
Bck2Brwsr, a Java VM that may compile ahead-of-time the java bytecode to javascript. It produces a javascript file for each .jar file.
You may use the vm javascript object to load a class into javascript and execute static methods (using vm.loadClass(.., function(class){..}}). There is an example in the documentation for the gradle plugin and the maven task.
TeaVM, is another Java VM that may convert ahead-of-time the code to javascript. In contrast to Bck2Brwsr, it supports threads, produces a single file for all your classes and provide better debugging support.
You may call java from javascript using the javaMethods.get(..).invoke(...) method.
DukeScript, transpile java code and bytecode to javascript using Bck2Brwsr or TeaVM.
It provides maven tasks to compile the java code. The resulting code (and technique to call java from javascript) depends on the used transpiler.
Dragome, transpile java bytecode to javascript.
You can annotate static methods in Java and use it in Javascript: e.g. you can annotate a method with #MethodAlias(alias="windows.method1") and invoke it from javascript using window.method1()
CheerpJ (a commercial product) may run complete java applications using Swing and AWT. It provides a very complete javascript environment that support operating system, thread and network functionalities.
It provides a complete runtime API. You can run a main method using cheerpjRunMain( <class>, <jar> ). You can create objects using cjNew( <class>, <params>...) and invoke static methods using cjCall( <class>,<method>,<params>...). There are many other methods you may consider.
Running Java code in Javascript
DoppioJVM is a complete JVM written in Typescript. Pros: It emulates a lot of elements of the operating system, including filesystems, TTY consoles and threads. Cons: Considering that it is an interpeter, it may result slower than other solutions. (I have not tested it)
DoppioJVM is a JVM written in Typescript
The documentation includes snippets of code to load and run the classes. You can run a static method using jvm.runClass( <class>, [ <args>...], function(response){..}). You can run a Jar file and perform many other tasks.
Create applications combining Java and Javascript
Some other solutions provide, not only the tools for compiling the code, but also frameworks and solutions to create java and javascript solutions. For instance, CheerpJ has complete versions of the Swing and AWT libraries for graphical user interfaces, but they may result very slow. You may replace the user interface by using new HTML versions that run faster on the browser. Pros: You can reuse existing code without changes, mainly some libraries and business logic. You may remove from your solutions libraries that run not efficiently in the browser. Cons: If you wanna keep maintaining your java desktop version, you must deal with different code for the browser.
GWT converts Java code to javascript but uses a different set of libraries for the user interface and client-to-server communications.
The documentation maintains information of differences with the JRE
You may export Java classes to be used by Javascript code.
Dukescript uses the conversion tools mentioned before.
It provides a Knockout4j library that may interact easily with HTM, DOM and additional javascript code.
Dragome not only convert java code but also include means to interact with the HTML/DOM
You may use annotations to bind java objects to HTML elements and to handle the DOM
HTML/Java API is an Apache project that standardize the access to HTML/DOM/javascript from transpiled code
It was donated by Dukescript and other tool providers.
Recommendation
If you wanna reuse few classes created by your own, you may try JSweet. You may create javascript modules (libraries) that you can use easily with javascript and typescript.
If you wanna reuse a medium to large codebase that rely on multiple java libraries, you may try CheerpJ, Dukescript or Dragome. You may reuse large parts of your code and create (gradually) the user interface and client-to-server communications using technologies that are more browser-friendly.
If you wanna run complete java applications without change, you may try CheerpJ. It can run Swing and AWT user interfaces. It also provide an Applet runner.
Here's two other options, things to look into and a third option not converting, just living together.
Java2Javascript
I have been wanting to try this out -- Looks closer to what's been asked. Quoting the web page:
an Eclipse Java to JavaScript compiler plugin and an implementation of JavaScript version of Eclipse Standard Widget Toolkit (SWT) with other common utilities, such as java.lang.* and java.util.*. You can convert your SWT-base Rich Client Platform (RCP) into Rich Internet Application (RIA) by Java2Script Pacemaker.
A limited Java in Javascript experience - You'd need to port your necessary dependencies or find alternatives via tools like jQuery, etc.
DukeScript
As I view DukeScript, it compiles some front-end Javascript and calls Java behind, from the browser's Javascript. It seems more or less a hybrid approach so you can use the Java wealth of libraries from Javascript. I will fall foul of a browser security policy for Java.
A more full-Javascript on Java experience leveraging the Java-runtime. If I wanted that outside the browser environment I'd use Javascript on Java.
Nashhorn
Consider this as an example of using Java's resources as foundation for Javascript: Nashorn and JavaFX, as an example for a rich Javascript operated client. Anyway with a Javascript engine inside Java you're not needing to translate between a Javascript-VM to object-code to a Java-VM quite so much.
Not entirely on-topic, but Kotlin is a 100% Java-compatible language that can compile to JavaScript.
IntelliJ IDEA can automatically convert Java to Kotlin and compile it to run on Node or the browser.
Given a set of Java source code files, how can I compile them into one
or more JavaScript files that can be used with hand-crafted
JavaScript?
There is no direct correlation between both the built-in Java API and Java language features, and those of JavaScript. So any attempt at creating a "converter" is going to be incomplete. As a fundamental example, Java classes don't have a direct corresponding JavaScript idiom.
Whether or not an incomplete conversion tool will work for your use case is impossible to know without the source code.
That said, my suggestion to solving your problem would be to first attempt to use GWT: set up a demo project, drop in the source of your library and call it from the JavaScript side and see what GWT outputs in it's .js file. Some of the other tools suggested by other posters here are definitely worth checking out as well.
If that is fruitful and gets you part of the way, great.
From there, you'll need/want to do the remainder of the conversion by hand. After all, assuming you want the code to actually function correctly, a manual review would definitely be in order. Some unit tests being converted along with it would be ideal as well.
You don't state how large the source of your project is, but if it's small (let's say less than a thousand lines of code), even a complete conversion by hand shouldn't be extremely difficult. If it's much larger than that, I would suggest reviewing if you actually want that as JavaScript code anyway.
This question is from 13 years ago; yes, I know. But I'll put my addition here as this is an excellent repository of answers on the topic, and as it comes up first in a Google search it is likely to have the most eyeballs on it.
I'm a former GWT developer. And agree it is an excellent solution & technology. But also yes as mentioned, the cross compilation part mostly (arguably, completely) focuses on the W in its name (Google WEB Toolkit): the client-side JavaScript part of full stack SPA Web applications, its serialization & communication, it's client/server logic partitioning, et al.
I just stumbled onto something that is relatively new -- a 2014-2015 offshoot of GWT placed into the public domain in 2018 -- that I think is more generally focused and what was being requested in the original post (13 years ago, lol). I'm eager to try it.
J2CL: https://github.com/google/j2cl
I read about it here, which to me was a good & thorough intro of the technology (have a look and let me know if you agree or not):
https://www.infoq.com/news/2019/05/j2cl-java-javascript-transpiler/
I've been doing a lot of reading about AJAX, and wanted to know which is the better way to approach things: by using a library such as jQuery using their built-in methods or creating JavaScript without a library for AJAX?
Ajax has a lot of quirks when working with the XMLHttpRequest Object. When you start to work with it, you will not see it, but when it is out in a production environment, it will bite you in the butt. Browsers, browser version, user settings, the type of server, type of request, and much more can affect what needs to be coded. Libraries tend to solve most of the problems, but they all are not perfect.
I always tell people it is great to work with a tutorial to see how the XMLHttpRequest works. After you have learned how to do it naked, work with a library that fits your needs.
Eric Pascarello
Why create a library when plenty already exists? If you create a library it is going to take time and effort and you'll end up going through the same hurdles others already have. And unless your company is trying to sell an Ajax library then stay away from writting your own plumbing code.
I am currently using both JQuery and Microsoft's Ajax in my site and have found that they are both feature complete with plenty of options of different ways you can set up the communication.
If you ask this question on comp.lang.javascript you'll get lots of different answers, many of which disdain the commonly-used libraries (one quote sometimes taken slightly out of context is Richard Cornford's post on c.l.js in 2007: "Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not the
best source of advice on designing systems that use javascript.")
The argument for libraries is they abstract away most of the differences between browsers and allow for cross-browser scripting. The argument against libraries is that they are bloated code with quirks of their own, so you'd have to learn just as much to use them well as you would to use cross-browser techniques in raw javascript. If you are writing lots of Javascript that you're going to reuse in multiple places, and you're trying to make websites that load quickly and use a minimum of excess bandwidth (e.g. if you have pay-per-use webhosting like via Amazon S3 or nearlyfreespeech.net), then it's probably worth stripping whatever you're going to use out of a good library, tweaking it, and using that.
I was all psyched about Prototype for a while, but then decided I just need a few simple building blocks. I tend to use Doug Crockford's simple JSON library, and then some of Fork Javascript's minimalist libraries as needed (primarily FORK.Ajax), and do the rest myself from scratch or reusing routines from an earlier project that I've honed to something that works well for me.
why wouldn't you use library if it meets your needs. you're using .net framework, or java JRE, or php built-in functions...
you can create your own javascript for the purpose of learning, or to do something libraries don't offer. but for regular development, you are much quicker with library and you get cross-browser compatible JS without having to code cross-browser support manually, it's already built-in into the library