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 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

const yourScriptName = () => {
  // your JS code here
}
export { yourScriptName }

JS application.js

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

// conditional trigger of your script
if (document.getElementById("jsTrigger-yourScriptName")) {
  yourScriptName();
  console.log("TRIGGERED : yourScriptName");
}

Clone this wiki locally