Loading Javascript assets
soumyaray opened this issue · 3 comments
I'm loving Roda, but I'm not sure how the assets plugin works. Here's what I'm doing to load a javascript file:
In controller app/controllers/app.rb
:
class App < Roda
plugin :assets, path: 'app/views/assets', css: 'style.css', js: 'my_script.js'
route do |routing|
routing.assets
The above alone does not load my_scrypt.js
in the browser (not seen in the resources list of the browser).
So in my layout template (views/layout.slim
) I add :
== assets(:js)
Now the browser shows my_script.js
in the resources list, but the script does not activate when it should (it's triggered by clicks on a particular div class).
So instead I put the line in my home page view (views/homepage.slim
) where I need it to work:
== assets(:js)
The script now works, but my_script.js
now shows up twice in my browser's resources list!
Any suggestions on what I'm doing wrong?
You need to defer the JavaScript from running before the <div>
you want to perform actions on is present in your page. When you load your assets in the layout, they JavaScript is running before the rest of the page loaded.
The simplest solution is to defer
your JavaScript until the page has been parsed.
== assets(:js, defer: true)
Questions like this are best asked on the IRC channel or Google Group, both of which have active members willing to help.
It sounds like there are a few questions you have, let me try to address each.
It is expected that just adding the plugin will not load the assets in the browser, you do need to call the assets
method in one of your views so that the link/script tags end up in the HTML the browser receives.
As to why it works in the home page view and not just in the layout, it may be related to where the tag ends up. If the layout puts the script tag before the content, and the script is designed to work with DOM elements already present, then that won't work. You could try changing your layout to put the script tags near the bottom of the page if you are not already doing that.
In any case, this is a question about how a plugin works and not a bug report. Per the contribution guidelines, you should ask such questions on the ruby-roda Google Group or on IRC. Please only post an issue on GitHub if you are fairly sure you have found a bug in Roda (either the core or one of the plugins that included in the gem). If you aren't sure it is a bug, it's best to ask on the Google Group or IRC first.
Many thanks for your guidance @jeremyevans and @adam12 . If I have further questions I'll take them to the IRC / Google Group.