javascript_include_tag(*sources) public

Returns an HTML script tag for each of the sources provided.

Sources may be paths to JavaScript files. Relative paths are assumed to be relative to assets/javascripts, full paths are assumed to be relative to the document root. Relative paths are idiomatic, use absolute paths only when needed.

When passing paths, the “.js” extension is optional. If you do not want “.js” appended to the path extname: false can be set on the options.

You can modify the HTML attributes of the script tag by passing a hash as the last argument.

When the Asset Pipeline is enabled, you can pass the name of your manifest as source, and include other JavaScript or CoffeeScript files inside the manifest.

javascript_include_tag "xmlhr"
# => <script src="/assets/xmlhr.js?1284139606"></script>

javascript_include_tag "template.jst", extname: false
# => <script src="/assets/template.jst?1284139606"></script>

javascript_include_tag "xmlhr.js"
# => <script src="/assets/xmlhr.js?1284139606"></script>

javascript_include_tag "common.javascript", "/elsewhere/cools"
# => <script src="/assets/common.javascript?1284139606"></script>
#    <script src="/elsewhere/cools.js?1423139606"></script>

javascript_include_tag "http://www.example.com/xmlhr"
# => <script src="http://www.example.com/xmlhr"></script>

javascript_include_tag "http://www.example.com/xmlhr.js"
# => <script src="http://www.example.com/xmlhr.js"></script>
Show source
Register or log in to add new notes.
July 20, 2010
4 thanks

When scripts don't end in .js

For example, Google Custom Search’s URL is http://www.google.com/jsapi

It’s an ugly hack, but works:

= javascript_include_tag('http://www.google.com/jsapi').sub('.js', '')
December 2, 2009
2 thanks

IE GOTCHA - multiple javascript_include_tags with cache => true

If you have multiple lines of javascript_include_tag ‘jsfile’, :cache => true, IE does not load them all (though it seems Firefox and Safari do). And the error won’t show up until you’re in production (since that’s only when caching kicks in.)

You should include them all on one line:

javascript_include_tag 'file1.js', 'file2.js', 'file3.js', :cache => 'myfiles'
July 10, 2010
2 thanks

Re: IE GOTCHA

@insane-dreamer

That has nothing to do with IE. When you specify :cache => true you are saying that the files referenced should be saved to a file called all.js. When the script encounters the next line, it will overwrite the same file with the new contents.

Caching is not compressing, it doesn’t make sense to do with individual files, but it can make sense some times. I someone wants to do it, just specify a name for the cached file:

javascript_include_tag 'layout', 'typography', :cache => 'base'
javascript_include_tag 'admin/layout', 'admin/extras', :cache => 'admin'