Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I include javascript assets selectively in SailsJS?

In a Sails.js application, how can I include javascript assets selectively?

For instance, if I have an admin page and admin.js lives inside the assets/js directory. How do I keep the admin.js from loading on the public index page?

I'm aware that I could move the js out to the public directory, and include the script in my admin view's template. But I'm still unable to include it after the assets.js() call inserts it's javascript. I need it to be inserted after the sails.io.js script is loaded.

Is there any way to selectively load scripts and still have access to the sails.io.js which is automatically included with the assets.js() function call? Is there a better paradigm for this kind of situation?

EDIT:

Since the release of SailsJS 0.9 and the restructuring of the asset management system, this question doesn't really apply anymore.

like image 212
albiabia Avatar asked Jun 09 '26 01:06

albiabia


1 Answers

In a Sails.js application, how can I include javascript assets selectively?

I selectively load js assets using a wrapper around assets.js(). This snippet uses Jade's "-" and "!{...}". EJS would instead use "<%...%>" and "<%=...%>"

<!-- JavaScript and stylesheets from your assets folder are included here -->
!{assets.css()}
-function selectAssets (assetsjs, files, ifInclude) {
-  return assetsjs.split('\n').reduce(function (prev, curr, i) {
-    var frag = curr.match(/src="\/assets\/js\/\w{1,}\-/);
-    if(frag) {
-      var file = frag[0].substring(16, frag[0].length - 1);
-      if ((files.indexOf(file) === -1) == ifInclude) { return prev; }
-   }
-   return prev + curr + '\n';
-  }, '');
-}
//!{assets.js()} this line is replaced by:
!{selectAssets(assets.js(), ['dummy1', 'dummy5', 'dummy6'], false)}

The above would not include /assets/js/dummy1.js, dummy5, dummy6 with the layout. If you wanted to include dummy1 and dummy5 on a particular page, you would place

!{selectAssets(assets.js(), ['dummy1', 'dummy5'], true)}

on that page.

Note: The code assumes file name don't contain "-". Its straighforward to generalize for css and templates. sails-io would be a special case for mixins.

like image 198
JohnSz Avatar answered Jun 11 '26 16:06

JohnSz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!