DOMContentLoaded和turbolinks:在第一页加载的情况下加载不动态加载的脚本(加载没有turbolinks)

时间:2018-03-27 11:03:30

标签: javascript ruby-on-rails turbolinks domcontentloaded dynamic-script-loading

'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解析之外执行的,但有没有办法实现所需的行为?

0 个答案:

没有答案