Sails.js - How to inject a js file to a specific route?

前端 未结 5 851
天涯浪人
天涯浪人 2020-12-13 07:39

For example, I have a page /locations/map which I need to include Google Map library, and include a .js file (e.g. location.js) specif

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 08:27

    This method allows flexibility to locally serve js files from any page and also prevent any reference errors caused by dependencies.

    In pipeline.js insert '!js/local/*.js at the bottom of jsFilesToInject like so:

    var jsFilesToInject = [
    
    // Load sails.io before everything else
    'js/dependencies/sails.io.js',
    
    // Dependencies like jQuery, or Angular are brought in here
    'js/dependencies/jquery-3.3.1.min.js',
    'js/dependencies/**/*.js',
    
    // All of the rest of your client-side js files
    // will be injected here in no particular order.
    'js/**/*.js',
    
    //Ignore local injected scripts
    '!js/local/*.js' 
    
    ];
    

    Create a local folder inside the /assets/js folder ie /assets/js/local/. Place any locally injected scripts in here.

    In your master view ejs ie layout.ejs insert <%- blocks.localScripts %> below the SCRIPTS block like this:

    
    
    
    
    
     
    <%- blocks.localScripts %>
    

    In your local ejs view (eg. homepage.ejs) insert your localScripts block like this:

    <% block('localScripts', '') %>
    

    sails v0.12.14

    EDIT Is this still relevant for Sails v1.0?

    My answer is a resounding YES and in my earlier answer I lacked explaining how to get the most out of the Grunt pipeline like clean, coffee, concat, uglify etc... when going into production.

    The trick here is to make a local file (there should only be one per page) as small as possible.

    • Group and name specific your function calls
    • Save functions as separate files for easy maintenance and group them into folders.
    • Group bindings and any initialising of global variables into a couple of functions like initThisPageVariables() and initThisPageBindings() so that Grunt can crunch these later.
    • Set a master function call to run your app startThisPageApp()

    Then simply calling the few functions from your local (master) file to get things rolling.

    $(window).on('load', function(){
    
       initThisPageVariables();
       initThisPageBindings();
    
       $(window).on("resize", function(){
          initThisPageVariables();
       }).resize();
    
       startThisPageApp(); 
    
    });
    

提交回复
热议问题