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.
  • Solution: one way is the following workflow:

HTML yourpage.html.erb

all our sites have a main container. Give this wrapper an id named following the pattern jsTrigger-yourScriptName (your-script-name.js is the file you want to run on this page!)

<!-- 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 = function(elementId) {
console.log("-----load : your-script-name.js");
  if (document.getElementById("jsTrigger-copyToClipboard")) {
    console.log("TRIGGERED : your-script-name.js");
  }
}
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