5

'turbolinks:load' 不会在直接加载的页面上被触发,但在加载了 turbolinks 'turbolinks:load' 事件的页面上工作正常。

<!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>

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" );
});

上述代码的浏览器控制台输出是

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

我知道这个问题是因为动态脚本是在 DOM 解析之外执行的,但是有没有办法实现所需的行为?

4

0 回答 0