The Impact of Speed and Performance on Generating Multiple HTML Templates using JavaScript Classes

Currently, I am in the process of developing a travel website using Ruby on Rails 4 which heavily relies on Javascript (or Coffeescript) for functionalities such as Google Maps and other APIs. The workflow involves making an initial call to the server, constructing a javascript object with the returned data, and promptly displaying some HTML content. Subsequently, there is a need to show different HTML based on the same dataset at a later stage.

A common scenario would be:

  1. User initiates a search for transportation between two locations
  2. Coffeescript sends an ajax post request to the rails server
  3. The rails server responds with a JSON object named searchResults, containing an array of routes (e.g.,
    searchResults['routes'][0]['path']
    or
    searchResults['routes'][0]['price']
    )
  4. The application instantly displays the search results in HTML format 1
  5. Later, upon user interaction, specific data about one of the routes needs to be displayed using a different HTML structure than in step 4 (format 2)

My current approach in Step 3 involves creating an instance of a SearchResults class in Coffeescript:

#holds all of the information for a single the transporation search call
class TransportationSearch
  constructor: (oLat, oLng, dLat, dLng, oName, dName) ->
    @origin = oName
    @destination = dName
    response = @search(oLat, oLng, dLat, dLng).responseJSON
    @longestRoute = response.longestRoute #in minutes
    @routes = response.routes

I chose to create a Coffeescript class to avoid additional server requests, which could slow down the performance considering API limits. My inquiry revolves around steps 4 and 5, where two different methods have been identified to meet my requirements, and I am curious about their speed/performance implications.

Method 1: Cloning Hidden Div

In this method, functions within TransportationSearch clone a hidden div, configure its attributes, and insert it into the DOM:

renderFormatOne: ->
    for route in routes
      content = $('.div-one-template').clone().removeClass('hidden')

      #...sets content for template. For example:
      content.find('.price').html(route['price'])

      #Insert template into Dom
      $('#results-one').append(content)

renderFormatTwo: ->
    ...

Method 2: Using AJAX/Rails to Render the HTML

An alternative approach involves storing the HTML templates in a Rails partial file and utilizing AJAX to transmit data to the controller to render the output.

Coffeescript:

showTransportation: (searchResults) =>
    $.ajax '/segments/side_menu_transportation',
      type: 'post'
      data:
        searchResults: JSON.stringify(searchResults)
      success: (data) ->
        $('#add-transport-box').html(data)
        return true
      error: ->
        alert 'passDestinationToTransportation Unsuccessful'
        return

    @show()

Controller:

def side_menu_transportation
  @searchResults = JSON.parse(params[:searchResults])
  render partial: 'trips/transport_search'
end

While Method 1 appears somewhat messy due to embedding the HTML structure in Coffeescript, prioritizing speed might influence my decision. Although I lean towards Method 2, I ponder if the AJAX POST request could potentially impact performance even without directly contacting the rails server.

I seek insights regarding the speed/performance consequences of these approaches, or any evident oversights that I may have missed :D.

Your feedback is greatly appreciated!

Answer №1

Sending data back to the server to generate HTML may not be the best practice, as it could be considered generating frontend on the backend, which seems a bit unusual and can impact UX by reducing UI responsiveness.

Concerns about JavaScript speed should not be a major issue, as frameworks like Angular constantly render HTML without significant browser impact, unless coding was done carelessly.

While including HTML in JavaScript is inevitable for frontend development, utilizing interpolated templates instead of manipulating DOM nodes directly can potentially decrease the number of costly DOM operations and improve template organization.

If server-side rendering of HTML is necessary (although not recommended), it's advisable to avoid making users wait by pre-rendering multiple templates simultaneously during the initial call.

Lastly, a helpful tip:

class TransportationSearch
  constructor: (oLat, oLng, dLat, dLng, oName, dName) ->
    @origin = oName
    @destination = dName

is equivalent to

class TransportationSearch
  constructor: (oLat, oLng, dLat, dLng, @origin, @destination) ->

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the API array index by checking the value of the 'Name' field

I am looking to compare the name of a button I click on with an array in order to find the matching name and then select the corresponding array number. Currently, I have a For loop that retrieves information from every team in the array, but I only requi ...

Using Three.js to load blender JSON files

Hey there! I'm currently facing some challenges when it comes to importing models from Blender into three.js. Currently, I am using the latest version of three.js (R71). I have successfully installed the three.js exporter in Blender and it works fine ...

Regex search without truncating repetitions

I am trying to locate patterns in strings where a character is followed by another character, and then followed by the first character again. For instance, in the string "abab" I am looking for "aba" and "bab". /([a-z])[a-z]{1}\1/g But when I run t ...

JQuery magic: Enhancing a div's visibility with animated mouseover effects

I'm trying to figure out how to animate a div on mouseover, specifically making it fade in/appear slowly. I believe I need to use the .animate function or something similar. $("#logo").mouseover(function() { $("#nav").css('visibility',&apos ...

Using Vue.js - Incorporate filtering functionality within the v-for loop

I've successfully implemented a Vue filter that restricts the length of an array to n elements. It functions perfectly when used like this: {{ array | limitArray(2) }} Now, I'm attempting to utilize it within a v-for loop as follows: <li v- ...

Concealing Panels within EasyUi Tab Navigation

There is an easyui Tab that consists of 4 tabs. After receiving a response from the server, it may be necessary to hide or show some of the tabs. I attempted to remove the tabs initially and add them back later. However, the issue arises when the tabs are ...

JavaScript cannot determine the length of an array of objects

I'm encountering an issue with an array of objects named tagTagfilter. When I log it in the browser, it doesn't immediately show the correct length value inside. tagTagFilter: TagFilter = { filterName: 'Tag', tags: [] ...

No matter how many times I modified the code in the ReactDOM.render() method within my index.js file, the end result remained unchanged

When I ran npx create-react-app my-app, and then proceeded to cd my-app and npm start, a browser opened on localhost:3000. While looking at the index.js file, I noticed that the ReactDOM.render() method included the following code: ReactDOM.render( <Rea ...

Invoke a function within one component using another component

I am facing an issue with deleting playlists displayed on my page. These playlists are fetched from an external API and each playlist has a delete button which is supposed to remove the playlist both from the API and the view. The deletion process works s ...

Can someone guide me on passing functions from a service to the controller and invoking them using AngularJS ES6 syntax?

Whenever I attempt to invoke the getTodos function in the controller, it seems to be returning no value. I am trying to store the value returned by the getTodos() function into this.todos. However, this.todos keeps returning null. /* ----- todo/todo.ser ...

Dropping and dragging in the Dojo for the nested lists

Within my HTML code, I am using the Dojo drag and drop feature to sort attributes and move them to another section. However, I am having trouble figuring out how to sort the sections themselves. Here is the structure that I have created: <ul accept=" ...

The Node js server operates by passively listening for incoming connections rather than actively establishing them

I have been working on setting up a node.js server to send emails to a specific email address using the sendgrid API. Everything was working perfectly until I attempted to deploy the server on Heroku. After deployment, the terminal shows that the server ...

Tips for Loading a Selected Option from an Ajax Call in Angular JS on Page Load

How do I automatically set the selected option from an ajax call when the page loads? I am fetching zones using an ajax call and I want to trigger the change function of the zones on page load in order to set the selected option of the cities select box. ...

Assign a value to the initial column of a row if the ID is found in the array

I'm attempting to set checkboxes within a specific range. The firebase_id array needs to correspond with column B in that range. If they match, the row should be set to TRUE. However, I am encountering issues where some checkboxes are randomly checked ...

Refresh HTML with JSON/AJAX

Ever since I discovered JSON for handling AJAX functionality in my rails applications, I've been hooked. Using RJS to render HTML just didn't sit right with me as it felt like it was violating the MVC pattern. My first project that heavily utiliz ...

Having difficulty entering text into the Material UI TextField

I am encountering an issue with a button that opens up a Material UI Dialog containing a TextField. However, I am unable to click into the TextField to input any text. Additionally, when clicking on the button to open the Dialog, I receive the error messag ...

Errors may sporadically occur during remote validation with messages stating "dictionary includes a null entry"

I am encountering a persistent error during remote validation when attempting to verify if a value already exists in the database: The parameters dictionary is exhibiting a null entry for the parameter 'gbsNumber' of non-nullable type 'S ...

Tips for integrating AsyncGenerators with Kotlin/JS

I am currently exploring the use of IPFS with Kotlin/JS, but my issue is not limited to that specific context. The functions ipfs.cat() and ipfs.get() return an AsyncGenerator, and I am uncertain about how to properly iterate over it using Kotlin (I am als ...

Using Q to conduct polling asynchronously with promises

I am facing a situation similar to the one discussed in this blog post: Polling with promises. The author explains using promises for polling until a JobID is returned. I intend to implement this using Q. I want to chain promises together but my attempts ...

Is there a way to convert arrow functions in vue files through transpilation?

I have developed a Vue application that needs to function properly in an ES5 browser (specifically iOS 9). One issue I've encountered is that some of the functions within the Vue components are being transformed into Arrow functions: ()=>, which i ...