Better encoding of javascript

Fixes #2988
Replaces #3005