最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ruby on rails - How do I load page javascript after async loading of my manifest file - Stack Overflow

programmeradmin4浏览0评论

I am trying to convert my app to asynchronous javascript loading with:

<%= javascript_include_tag "application", async: true %>

The problem is that any page-specific scripts are being run before Jquery is loaded asynchronously. How can I defer those until the application.js manifest file has been loaded.

I tried wrapping my page js in $(window).load(function(){}); but this did not help. I still see the following error:

Uncaught ReferenceError: $ is not defined

Update:

This seems to be working for me, but I'd like someone to confirm that it is the correct approach:

<%= javascript_include_tag "application", async: true, onload: 'pageScripts()' %>

Then the page script like:

<script>
  function pageScripts() {
    // do something
  }
</script>

I am trying to convert my app to asynchronous javascript loading with:

<%= javascript_include_tag "application", async: true %>

The problem is that any page-specific scripts are being run before Jquery is loaded asynchronously. How can I defer those until the application.js manifest file has been loaded.

I tried wrapping my page js in $(window).load(function(){}); but this did not help. I still see the following error:

Uncaught ReferenceError: $ is not defined

Update:

This seems to be working for me, but I'd like someone to confirm that it is the correct approach:

<%= javascript_include_tag "application", async: true, onload: 'pageScripts()' %>

Then the page script like:

<script>
  function pageScripts() {
    // do something
  }
</script>
Share Improve this question edited Mar 7, 2016 at 15:33 Abram asked Mar 7, 2016 at 15:15 AbramAbram 41.9k28 gold badges138 silver badges186 bronze badges 1
  • Why not simply write your javascript inside a window.onload scope ? – jayant Commented Aug 16, 2016 at 10:44
Add a ment  | 

1 Answer 1

Reset to default 17

Your approach is correct however I would suggest to limit your Async only for production since in development Sprockets hasn't concatinated all of the files yet.

<%= javascript_include_tag "application", async: Rails.env.production?, onload: 'pageScripts()' %>
发布评论

评论列表(0)

  1. 暂无评论