DOMContentLoaded and turbolinks:load not triggering on Dynamically loaded scripts with first page load (loaded without turbolinks)
Asked Answered
B

0

6

'turbolinks:load' is not getting triggered on the directly loaded pages but, on the pages loaded with turbolinks 'turbolinks:load' event is working fine.

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="https://rawgit.com/turbolinks/turbolinks/master/dist/turbolinks.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>
        test
    </title>
    <script>
      function loadScript(src) {
        if(!document.querySelector("script[src='"+src+"']")){
          var n = document.createElement("script");
          n.src = src;
          n.async = false;
          document.getElementsByTagName("head")[0].appendChild(n);
        };
      };
    </script>
  </head>
  <body>
    <p style='color:red'>
      Hi Priority Rendering With inline css to improve start render
    </p>
    <script type="text/javascript">
      loadScript("dynamic_load_turbolinks_script.js");
    </script>
  </body>
</html>

Code of dynamic_load_turbolinks_script.js

console.log('This file will contain all functionally required script');
document.addEventListener("turbolinks:load", function() {
  console.log('Inside turbolinkss Load')
});
window.onload = function(){
  console.log('Inside window onload')
};
document.addEventListener('DOMContentLoaded', function(){
  console.log('Inside DOMContentLoaded')
});
$(document).ready(function() {
  console.log( "Inside document ready" );
});

Browser Console output of above code is

dynamic_load_turbolinks_script.js:1 This file will contain all functionally required script
dynamic_load_turbolinks_script.js:6 Inside window onload
dynamic_load_turbolinks_script.js:12 Inside document ready

I know that the issue is because dynamic scripts are executed outside of DOM parsing but, is there any way to achieve the desired behavior?

Betteanne answered 27/3, 2018 at 11:3 Comment(1)
Same problem here :(Approximation

© 2022 - 2024 — McMap. All rights reserved.