Webpack(er): A primer
webpack is a very powerful asset bundler written in node.js to bundle (ES6) JavaScript modules, stylesheets, images, and other assets for consumption in browsers.
Webpacker is a wrapper around webpack that handles integration with Rails.
This is a short introduction.
Installation
If you haven't already, you need to install node.js and Yarn.
Then, put
gem 'webpacker', '~> 4.x' # check if 4.x is still cu...
How to access Chrome Devtools when running JavaScript tests via CLI
While we are used to run our JavaScript tests on a test page within our Browser, it's also possible to run them on the command line with NodeJS. I think that's actually the most common way to run JS tests.
Given a Vue project that uses Jest (via vue-cli-service
) with the following package.json
:
{
"scripts": {
"test": "vue-cli-service test:unit --testMatch='**/tests/**/*.test.js' --watch"
},
}
This allows us to run J...
JavaScript: Working with Query Parameters
tl;dr: Use the URLSearchParams
API to make your live easier if you want to get or manipulate query parameters (URL parameters).
URLSearchParams
API
The URLSearchParams
API is supported in all major browsers except IE 11.
It offers you a bunch of useful methods:
-
URLSearchParams.append()
- appends a query parameter -
URLSearchParams.delete()
- deletes the specified query parameter -
URLSearchParams.get()
- returns the value of the specified query parameter - `URLSearchP...
Google Chrome now has a JavaScript bundle visualizer
Similar to the Webpack Bundle Analyzer, Chrome's new Lighthouse feature …
… shows a visualisation of your JavaScript bundles. It's compatible with sourcemaps and is great for understanding large JavaScript modules used by your page. It can also visualise unused bytes.
This is very helpful to visualize Javascript files in development. It also works on production code, where its usefulness depends on the structure of the productive Javascr...
Managing vendor libraries with the Rails asset pipeline
The benefit of the Rails asset pipeline is that it compiles your stylesheets and javascripts to a single file, respectively. However, the consequences are startling if you don't understand them. Among others, the raw asset pipeline requires you to have all your asset libraries in the same folder, which quickly becomes confusing as your set of assets grows. To overcome this, we have two different solutions.
Custom solution
We are using a custom workaround to keep library files apart in their own directories. To avoid b...
Trigger a link's click action with Javascript
Use the click
method on the DOM element:
let link = document.querySelector('a')
link.click()
Detecting when fonts are loaded via JavaScript
Webfonts are not always available when your JavaScript runs on first page load. Since fonts may affect element sizes, you may want to know when fonts have been loaded to trigger some kind of recalculation.
Vanilla JavaScript / Modern DOM API
In modern browsers (all but IE and legacy Edge) you can use document.fonts
. Use load
to request a font and receive a Promise that will be resolved once the font is available. Example:
document.fonts.load('1rem "Open S...
JavaScript: How to query the state of a Promise
Native promises have no methods to inspect their state.
You can use the promiseState
function below to check whether a promise is fulfilled, rejected or still pending:
promiseState(promise, function(state) {
// `state` now either "pending", "fulfilled" or "rejected"
});
Note that the callback passed to promiseState
will be called asynchronously in the next [microtask](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/...
A tracer utility in 2kb « JavaScript, JavaScript
Inspired by a snippet of code in Oliver Steele’s legendary Functional library, here’s a lightweight tool to help keep track of JavaScript invocations. It works in Chrome, Safari, Firebug and IE8.
Why your javascripts should be executed after the dom has been loaded
Most of the JavaScript snippets have code that manipulates the DOM. For that reason dom manipulating javascript code should have been executed after the DOM has loaded completely. That means when the browser has finished HTML parsing and built the DOM tree. At that time, you can manipualte the DOM although not all resources (like images) are fully loaded.
The following snippets show how you can do this with plain JavaScript, jquery or prototype ([dom ready ...
CoffeeScript
Imagine all the syntactical delights of Ruby and Haml for your JavaScript. You write in a nice language, but get normal JavaScript at runtime. All whilst having full access to 3rd-party JavaScript libraries (jQuery, PrototypeJS), debugging support (it becomes pure, readable JavaScript), existing support from test suites (it’s normal JavaScript) and growing support from various text editors (TextMate, Vim, Emacs).
Minified JavaScript and CSS
JavaScripts and CSS should be minified for production use.
In Rails 3.1+ the asset pipeline will take care of this. Thus you're best off using an uncompressed version of your Javascript in development. Also load the non-minified versions of libraries. This way debugging will be easier and you will still get all the minification love once deployed.
In Rails 2.3 and 3.0 you should at least embed external JavaScript libraries in minified form, using something like JavaScript compressor.
Asset pipeline may break Javascript for IE (but only on production)
If some of your JavaScripts fail on Internet Explorer, but only in staging or production environments, chances are that JavaScript compression is the culprit.
By default, Rails 3.2 compresses JavaScript with UglifyJS. I have seen a few cases where this actually breaks functioning JavaScript on IE (one example is the CKEditor).
I fixed this by switching to Yahoo's YUI Compressor.
To do this, do the following:
- replace the
uglifier
gem with theyui-compressor
gem...
TodoMVC - A common learning application for popular JavaScript MV* frameworks
Developers these days are spoiled with choice when it comes to selecting an MV* framework for structuring and organizing JavaScript web apps. Backbone, Spine, Ember (SproutCore 2.0), JavaScriptMVC... the list of new and stable solutions goes on and on, but just how do you decide on which to use in a sea of so many options?
To help solve this problem, we created TodoMVC - a project which offers the same Todo application implemented using MV* concepts in most of the popular JavaScript MV* frameworks of today.
Solutions look and feel the same...
markbates/coffeebeans
When CoffeeScript was added to Rails 3.1 they forgot one very important part, the ability to use it when responding to JavaScript (JS) requests!
In Rails 3.1 it’s incredibly easy to build your application’s JavaScript using CoffeeScript, however if you fire off an AJAX request to your application you can only write your response using regular JavaScript and not CoffeeScript, at least until CoffeeBeans came along.
Keeping web applications fast
Our applications not only need to be functional, they need to be fast.
But, to quote Donald Knuth,
premature optimization is the root of all evil (or at least most of it) in programming
The reasoning is that you should not waste your time optimizing code where it does not even matter. However, I believe there are some kinds of optimizations you should do right away, because
- they are either obvious and easy
- or they are very hard to do optimize later
This is an attempt to list some of those things:
On the server
...
Cucumber: Detect if the current Capybara driver supports Javascript
Copy the attached file to features/support
. This gets you a convenience method:
Capybara.javascript_test?
Is true
for Selenium, capybara-webkit, Poltergeist and a custom driver called :chrome
(which we sometimes like to use for Selenium+Chrome).
Similar sounding but completely different card: Detect if a Javascript is running under Selenium WebDriver (with Rails)
sstephenson/execjs - GitHub
ExecJS lets you run JavaScript code from Ruby. It automatically picks the best runtime available to evaluate your JavaScript program, then returns the result to you as a Ruby object.
JSONP - Wikipedia
Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is the HTML <script> element. Taking advantage of the open policy for <script> elements, some pages use them to retrieve Javascript code that operates on dynamically-generated JSON-formatted data from other origins. This usage pattern is known as JSONP. Requests for JSONP retrieve not JSON, but arbitrary JavaScript code.
Thoughtbot's experiences with headless Javascript testing
Selenium has been the siren song that continually calls out to us. Unfortunately, in practice we’ve been unable to get Selenium to run reliably for real applications, on both developers machines and on the continuous integration server. This failure with Selenium has caused us to search for alternative solutions
Validatious 2.0 - Easy form validation with unobtrusive JavaScript
validate( "email".is("required").andIsAn("email") );
jspdf - Project Hosting on Google Code
jsPDF is an open-source library for generating PDF documents using nothing but Javascript. You can use it in a Firefox extension, in Server Side Javascript and with Data URIs in some browsers.
Underscore.js
Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It's the tie to go along with jQuery's tux.