-
Notifications
You must be signed in to change notification settings - Fork 1
Organising Javascript Code
Thomas Starzynski edited this page May 30, 2019
·
7 revisions
- 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:
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>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 }// app/javascript/packs/application.js
// import your script
import { yourScriptName } from "../components/your-script-name";
// run (trigger) your script
yourScriptName();