Skip to content

Organising Javascript Code

Thomas Starzynski edited this page May 30, 2019 · 7 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.

HTML yourpage.html.erb

All our sites have a main container. Give this container an id named following the pattern: jsTrigger-yourScriptName (your-script-name.js is the file you want to run on this page! Ensure the javascript file is kebab-case and the id of the main container div is lowerCamelCase)

<!-- app/views/.../yourpage.html.erb -->
<div class="background-container" id="jsTrigger-yourScriptName"> 
  <div class="master-container">
    <!-- CODE -->
  </div>
</div>

JS your-script-name.js

// conditional trigger of your script
const yourScriptName = () => {
  console.log("-----load : yourScriptName");
  if (document.getElementById("jsTrigger-yourScriptName")) {
    console.log("TRIGGERED : yourScriptName");
    // 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";

// run (trigger) your script
yourScriptName();

Clone this wiki locally