-
Notifications
You must be signed in to change notification settings - Fork 1
Organising Javascript Code
Thomas Starzynski edited this page Jun 1, 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.
- 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.
All our sites have a main container. Add a class to this container named with the 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
-
classof the main containerdivis lowerCamelCase - function that gets triggered is lowerCamelCase
<!-- app/views/.../yourpage.html.erb -->
<div class="jsTrigger-yourScriptName background-container">
<div class="master-container">
<!-- CODE -->
</div>
</div>// main function 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 }// 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)
// use the helper function `triggerJsOnTarget`
triggerJsOnTarget(yourScriptName, "jsTrigger-yourScriptName");