Ariel Rodriguez Romero

Lazily load jquery selectors

It’s a known bad practice to repeat in your code different calls to jquery with the same selector, so often the recommended way is to call those in a variable.But what happens when you want to refer to many different selectors??

Another thing I have been trying is to avoid adding CSS classes in javascript code, and rather pass them as options of the functions/classes in the code.

For that I created this little method, that given an object where you can specify the different selectors makes all the jquery calls automatically.

  function loadSelectors(sel) {
    var result = {}
    for (var i in sel) {
      result[i] = (function() {
        var element;
        return () => element || (element = $(i));
    return result;

The usage is pretty simple:

let selectors = {
	container: '.js-container',
	sidebar: '.js-sidebar'
let $selectors = loadSelectors(selectors);


The resulting object $selectors contains functions that will return the corresponding objects, but wrapped into jquery calls. The good thing is that they are lazily loaded and thus they are only called once.

Related posts

Deploying a serverless NextJS App

We migrated to NextJS recently and started using ZEIT to deploy our frontend. We required some configuration and even found a bug on ZEIT’s platform in the process.

Set up end-to-end tests with jest-pupeteer and NextJS

This contains details and the configuration files required to setup jest-pupeteer for end-to-end testing in a NextJS app.

Get route information from Google Flights

Simple strategy to scrape information from google flights (with manual work). It’s helpful if you don’t need a lot of information.