Skip to main content
Home  › ... Razor

turnOn Tutorials

Tutorial HometurnOn

Await system scripts

This page waits for a system script to load, then executes a JavaScript function with turnOn and passes a domAttribute as parameter. The executed JavaScript then triggers a system script, which binds the fancybox properties.


In this tutorial you'll learn how to:
  • Execute a JavaScript function after a system script was loaded
Look at the element below to see the effect.

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@inherits Custom.Hybrid.Razor12
@using ToSic.Sxc.Services;
@using ToSic.Razor.Blade;
<!-- unimportant stuff, hidden -->
Await system scripts This page waits for... <!-- unimportant stuff, hidden -->
<!-- unimportant stuff, hidden -->

@{
  // Use the PageService to activate turnOn and a system script
  GetService<IPageService>().Activate("turnOn", "fancybox4");
  
  // Create unique DOM attribute with Module Id
  var uniqueDomAttrubute = "turn-on-example-" + CmsContext.Module.Id;
}


@* Inject attribute into DIV, to make it accessible for query *@
<a @uniqueDomAttrubute href='https://images.unsplash.com/photo-1503899036084-c55cdd92da26?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80' data-caption="System script used here">
    <img loading="lazy" class="img-fluid" src='https://images.unsplash.com/photo-1503899036084-c55cdd92da26?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=250&q=80'/>
</a>

@* 
  Wait for the system script to load, 
  then execute the window.turnOnTutorial202.init function 
  and pass the domAttribute as JSON 
*@

<turnOn turn-on='{
  "await": ["window.Fancybox"], 
  "run": "window.turnOnTutorial202.init()", 
  "data": { "domAttribute": "@uniqueDomAttrubute" } }'></turnOn>

@* Include local JavaScript file *@
<script src="@App.Path/turn-on/_202-system scripts.js"></script>

<!-- unimportant stuff, hidden -->

Source Code of _202-system scripts.js

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

// Use an IFFE to ensure the variables are not exposed globaly
// See https://developer.mozilla.org/en-US/docs/Glossary/IIFE
(() => {
  // The init function which should be called
  function init({ domAttribute }) {
    // Example element gets found in the DOM and bound to Fancybox
    Fancybox.bind(`[${domAttribute}]`);
  }

  const tt = window.turnOnTutorial202 = window.turnOnTutorial202 || {};
  tt.init = tt.init || init;
})();