如何使用 requireJs & Backbone 加载动态视图 css 文件

How to load a dynamic view css file using requireJs & Backbone

我需要每个视图在导航到视图时加载它自己的 css 文件。 当前 css 文件已加载(我可以在网络部分看到它已加载)但它不影响页面样式

有什么想法吗?

define([
    'jquery',
    'text!../templates/Login.html',
    'text!../css/styleshet.css'
], function($, html, css){      

});

显然您需要手动将其添加到您的页面... 固定的是:

define([
    'jquery',
    'text!../templates/Login.html',
    'text!../css/styleshet.css'
], function($, html, css){      

//this will remove the old view css 
if ($("#customCss").length > 0)
            $("#customCss").empty();

//this will add the current css to the page 
 $('head').append('<style type="text/css" id="customCss"> ' + css + '</style>');

});

感谢Radek Michna

在您的 main.jsrequirejs script 标签data-main 属性中描述的文件中:

(function(){        
    requirejs.config({
        baseUrl: 'ASSETS',
        paths: {
            YOURJS: 'PATH/TO/JS/YOURJS'
        },
        shim: {
            "YOURJS": {
                "deps": ['css!PATH/TO/CSS/YOURCSS']
            },
        }
    });
})();

在同一目录中创建css.js文件baseUrl选项:

define({
    load: function (url, req, onLoad, config) {
        var head  = document.getElementsByTagName('head')[0];
        var link  = document.createElement('link');
        //link.id   = ;
        link.rel  = 'stylesheet';
        link.type = 'text/css';
        link.href = config.baseUrl+url+'.css';
        link.media = 'all';
        head.appendChild(link); 
        onLoad();                       
    }       
});