anguler 画面布局适应屏幕大小_angularJS窗口大小调整问题

在尝试实现AngularJS应用中窗口大小调整时,遇到了内存泄漏问题,导致高内存占用。问题起因于持续调整窗口大小,当窗口宽度小于640px时改变布局。解决方案是使用CSS媒体查询或优化AngularJS指令,移除不必要的$watch,以减少内存消耗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

So somehow I made a memory leak in JS. Well I only continously resized a window of my page, and then buum, 86% memory usage. out of 16gbs of memory. After I shut everything down I had to restart my pc because it still said 72% usage. System takes only 17%.

So I don't really understand whats happening there, all I wanted to somehow react when the user resizes the window because then I'd change the layout if the width is less than 640px for instance.

But yea here is my code.

Index.html:

random content
random content2

The idea was , I have the left and right side, after the screen width below 640px, I push them under each other by attaching a .fullw { width: 100% } style to them.

My directive:

.directive('resize', function ($window) {

return function (scope, element, attr) {

var w = angular.element($window);

scope.$watch(function () {

return {

'h': w.height(),

'w': w.width()

};

}, function (newValue, oldValue) {

if(newValue.w <= 640) {

scope.smallR = 1;

} else {

scope.smallR = 0;

}

}, true);

w.bind('resize', function () {

scope.$apply();

});

};

})

Its eventually working however if I start to play with it by resizing all day long, it starts to use tremendeous amount of RAM...

Thanks in advance

解决方案

You should just use CSS media queries for this task. Simple rule in your case:

.fullw {

width: 100px;

}

@media (min-width: 640px) {

.fullw {

width: 100%;

}

}

Or if you still want to use power of angular directive, remove $watch part, as you don't need it, it brings unnecessary overhead:

.directive('resize', function($window) {

return function(scope, element, attr) {

var w = angular.element($window);

w.on('resize', function() {

scope.smallR = w.width() <= 640 ? 0 : 1;

scope.$apply();

});

};

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值