How to load css by using requirejs?

强颜欢笑 提交于 2019-12-11 01:20:16

问题


This is my requirejs config file. I'm using require js on my angular based project. If I could load css with requirejs I would be able to organize my css files too! I'm new to requirejs concept. Any help appreciated

require.config({
    paths:{
        'angular'       : "agular",
        'app'           : 'app',
        'coreModel'     : 'coreModel',
        'test'          : 'controller/test'
    },
    shim: {
        'app' : {
            deps :['angular','coreModel',]
        },

        'coreModel' : {
            deps : ['angular','test']
        },
        'test' : {
            deps : ['angular',]
        }
    },
});

require(['app',],function(){
    angular.bootstrap(document,['app']);
});

This is my main controller

define(function(){

    var coreModel = angular.module('coreModel',['test']);

    coreModel.controller('mainController',function($scope){
        $scope.test = "Hello World";
    });
});

How can I load css with requirejs ?


回答1:


I would rather suggest you to something different using a ocLazyLoad.

Reference to my answer here

Follow the initial steps of the above link for configuration

I would suggest you to use this way in your Controller file as below

(function () {
    angular.module('myApp').controller("homeCtrl", function ($ocLazyLoad,$scope) {

          //this line loads your styles and apply it 
          $ocLazyLoad.load('style.css');

});
})();

LIVE DEMO

Note: In the demo click on the menu- > click home




回答2:


Taken from the requirejs documentation:

Since knowing when the file has loaded is not reliable, it does not make sense to explicitly support CSS files in RequireJS loading, since it will lead to bug reports due to browser behavior. If you do not care when the file is loaded, you can easily write your own function to load CSS on demand by doing the following:

function loadCss(url) {
    var link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = url;
    document.getElementsByTagName("head")[0].appendChild(link);
}

But you can use requirecss to make it work as simple as requirejs does:

  • Install require-css with bower install require-css
  • Configurate your application

    map: {
      '*': {
        'css': 'require-css/css' // or whatever the path to require-css is
      }
    }
    
  • Add your files for requirecss like you did it in requirejs

    define(['css!styles/main'], function() {
       //code that requires the stylesheet: styles/main.css
    });
    


来源:https://stackoverflow.com/questions/42532079/how-to-load-css-by-using-requirejs

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