Skip to content

LiistWeb Organising JS Code

Thomas Starzynski edited this page Jul 24, 2019 · 2 revisions

Javascript

  • Problem: Webpack packs all javascripts in one file, such that each javascript code is executed on every page! This can lead to unwanted issues and should be tackled in some way such that our website does not break.
  • The following workflow allows us to ensure that all javascript files get triggered in the right place and do not cause errors or unpredictable bugs.
  • disclaimer: this does not mean that only the needed javascript is loaded when need, still all javascript is loaded on every page, but its only triggered on the correct page! (no advantage when it comes to pageload speed!)

HTML yourpage.html.erb

Add a hidden input field with a class named with the following the pattern: jsTrigger-yourScriptName (your-script-name.js is the file you want to run / trigger on this page)! Ensure Naming conventions:

  • javascript file is kebab-case
  • class of the main container div is lowerCamelCase
  • function that gets triggered is lowerCamelCase
<!-- app/views/.../yourpage.html.erb -->
<input class="jsTrigger-yourScriptName" type="hidden">

JS your-script-name.js

// main function of your script
const yourScriptName = () => {
  console.log("TRIGGERED : yourScriptName"); // add this console log to monitor which script get triggered!
  // all you JS code goes here!
  // it only get triggered when we are on the right page!
}
export { yourScriptName }

JS application.js

// app/javascript/packs/application.js
// import your script
import { yourScriptName } from "../components/your-script-name";

// conditionally trigger your script (if the right page is loaded)
// use the helper function `triggerJsOnTarget`
triggerJsOnTarget(yourScriptName, "jsTrigger-yourScriptName");

Clone this wiki locally