我在MVC项目中加载了一些外部JavaScript和一些内联JavaScript来查看页面。我听说响应过滤器在内容加载后将这些脚本移动到页面的末尾,但我对此没有确切的了解。
我如何在我的整个项目中实现这一点?
我会使用构建任务(无论是使用Grunt或Gulp)来组合和缩小你的脚本作为静态内容,并重写你的HTML,包括CSS和JS资源,你想在你的页面。
您可以使用Gulp任务,如https://www.npmjs.com/package/gulp-uglify来组合和缩小,然后https://github.com/jonkemp/gulp-useref
整个任务看起来像这样:
gulp.task('html', function () {
var assets = useref.assets();
return gulp.src('app/*.html')
.pipe(assets)
.pipe(gulpif('*.js', uglify()))
.pipe(gulpif('*.css', minifyCss()))
.pipe(assets.restore())
.pipe(useref())
.pipe(gulp.dest('dist'));
});
除了最小化和组合资产之外,它还允许您定义要输出的HTML的哪个部分:
<html>
<head>
<!-- build:css css/combined.css -->
<link href="css/one.css" rel="stylesheet">
<link href="css/two.css" rel="stylesheet">
<!-- endbuild -->
</head>
<body>
<!-- build:js scripts/combined.js -->
<script type="text/javascript" src="scripts/one.js"></script>
<script type="text/javascript" src="scripts/two.js"></script>
<!-- endbuild -->
</body>
</html>
然后重写成这样:
<html>
<head>
<link rel="stylesheet" href="css/combined.css"/>
</head>
<body>
<script src="scripts/combined.js"></script>
</body>
</html>