Conditional javascript require in the asset pipeline

☆樱花仙子☆ 提交于 2019-12-06 09:18:56

I suggest you use yepnope, a lightweight library for loading libraries like this in parallel (for speed) and it gives you the option to run some other code to test if the library is loaded. For example:


yepnope([{
  load: 'http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js',
  complete: function () {
    if (!window.jQuery) {
      yepnope('asset_path('you_local_copy_of_dojo') ');
    }
  }
}])

(Note: You will need erb tags around the asset_path helper)

The local dojo file would be in the assets/javascript folder, but not included in the application manifest. You need to add the dojo file to the precompile array:

config.assets.precompile += 'your_local_file.js'

And this will make it available to the asset_path helper.

Thanks Richard!

I don't want to have yepnope to load one library. It would be overkill imo. Here is the solution I came up with, based on your help (written in slim):


1/ In vendors/assets/javascripts/, I have my dojo.js.

2/ In config/application.rb:

# Precompile these assets files
config.assets.precompile += ['dojo.js']

3/ In the template:

= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/dojo/#{Settings.dojoVersion}/dojo/dojo.xd.js", :'data-dojo-config' => %Q(dojoBlankHtmlUrl:'/blank.html', baseUrl: 'assets/', modulePaths: {custom: 'javascripts/modules'})
script = "typeof(dojo) === \"undefined\" && document.write(unescape('%3Cscript src=\"#{asset_path('dojo')}\"%3E%3C/script%3E'));".html_safe

I also posted on the Rails Google Group to request the addition of two options to the javascript_include_tag, :test and :local that would take care of all the work. We'll see.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!