test.html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <title></title> <style> .invisible { visibility: hidden; } #box1 { height: 1000px; background: #F00; } #box2 { height: 100px; background: #0F0; } </style> </head> <body> <div id="box1">box1</div> <textarea class="jq-datalazyload invisible"> <script> alert('222'); </script> <div id="box2">box2</div> </textarea> <script src="jquery-1.6.4.min.js"></script> <script src="datalazyload.js"></script> <script> var lazy = new $.Datalazyload() lazy.init() </script> </body> </html>
datalazyload.js
/** * Created with JetBrains PhpStorm. * User: Administrator * Date: 13-6-18 * Time: 下午2:13 * To change this template use File | Settings | File Templates. */ (function($) { var AREA_DATA_CLS = "jq-datalazyload"; function Datalazyload(config) { var defaultConfig = { }; this.setting = $.extend(defaultConfig, config || {}); } $.extend( Datalazyload.prototype, { init: function() { var self = this; self._getAreaList(); for (var i = 0; i < self.areaList.length; i++) { self._loadAreaItem(self.areaList[i]); } $(window).bind("scroll resize", function() { self._getAreaList(); for(var i = 0; i < self.areaList.length; i++){ self._loadAreaItem(self.areaList[i]); } }); }, _getAreaList: function() { var self = this; var areaList = []; areaList = $("textarea").filter("." + AREA_DATA_CLS); self.areaList = areaList; if (areaList.length == 0) { $(window).unbind("scroll resize"); } }, _replaceArea: function(area) { var self = this; var _area = $(area); var _html = _area.val(); _area.removeClass(AREA_DATA_CLS); $(_html).insertBefore(_area); _area.hide(); }, _loadAreaItem: function(area) { var self = this; var top; var viewHeight = $(window).height(); var scrollTop = $(window).scrollTop(); if ($(area).offset().top != 0) { top = $(area).offset().top; } else { top = $(area).parent().offset().top; } if (top <= viewHeight + scrollTop) { self._replaceArea(area) } } } ); $.Datalazyload = Datalazyload; })(jQuery);