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 Naming conventions:

  • javascript file is kebab-case
  • id of the main container div is lowerCamelCase
  • function that gets triggered 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("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)
if (document.getElementById("jsTrigger-yourScriptName")) {
  yourScriptName();
}

Clone this wiki locally