分类 js 下的文章

<script type="text/javascript">
            // 模拟一个异步函数,返回一个 Promise,最终解析出某个值,比如用户ID
            function fetchData() {
              return new Promise((resolve, reject) => {
                  //发动网络请求
                  //成功回调 resolve(userId);
                  //失败回调 reject(res);
                // 模拟异步操作,比如网络请求
                setTimeout(() => {
                  const userId = 12345; // 假设我们从某处获取到了用户ID
                  console.log('fetchData 执行完成,得到 userId:', userId);
                  resolve(userId); // 返回的值可以被下一个 .then() 接收
                }, 1000); // 模拟1秒延迟
                //请求出错
                //reject(res);
              });
            }

            // 模拟另一个异步函数,需要使用上一个函数的结果
            function processData(userId) {
              return new Promise((resolve, reject) => {
                setTimeout(() => {
                  console.log('processData 执行,处理的 userId 是:', userId);
                  const result = `用户 ${userId} 的数据处理完成`;
                  resolve(result); // 最终结果
                }, 1000);
                //请求出错
                //reject(res);
              });
            }

            // 使用 Promise 链式调用
            //fetchData().then((userId) => {return processData(userId);}).then((finalResult) => { console.log('最终结果:', finalResult);}).catch((error) => { console.error('出错了:', error);});

            //语法糖形式
            async function main() {
              try {
                const userId = await fetchData();         
                const finalResult = await processData(userId);  
                console.log('最终结果:', finalResult);
              } catch (error) {
                console.error('出错了:', error);
              }
            }

            // 调用主函数
            main();
</script>

时间紧、面向现代用户:选 loading=lazy。

需全兼容或复杂效果:用 lazyload 插件。

折中方案:用 loading=lazy 为主,针对不支持的浏览器引入轻量级插件:

<script>
if ('loading' in HTMLImageElement.prototype === false) {
  var script = document.createElement('script');
  script.src = 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.2/lazysizes.min.js';
  document.body.appendChild(script);
}
</script>
<img src="your-image.jpg" alt="示例图片" loading="lazy" class="lazyload">

function detectIE() {var ua = window.navigator.userAgent;var msie = ua.indexOf('MSIE ');if (msie > 0 && window.parseInt(navigator.appVersion.split(";")[1].replace(/[ ]/g, "").replace("MSIE", "")) <= 10) {return true;}
    //var trident = ua.indexOf('Trident/');if (trident > 0) {return true;}
    return false;}
function isIE(){var ua=window.navigator.userAgent;var msie=ua.indexOf('MSIE ');if(msie>0){return true}var trident=ua.indexOf('Trident/');if(trident>0){return true}return false}function ieFix(el,className){if(el.classList){el.classList.add(className)}else{el.className+=' '+className}}function isIos(){var a=navigator.userAgent;a=/iPad|iPhone|iPod/.test(a)||/Mac OS X/.test(a);var b=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;var htmlElement=document.documentElement;htmlElement.classList.remove("isIos","isIpadPro","isIpadAir");if(a){htmlElement.classList.add("isIos");if(b===1366){htmlElement.classList.add("isIpadPro")}if(b===820||b===1180){htmlElement.classList.add("isIpadAir")}}}function isMobile(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}
function fontSize(){var size;var a=window.innerWidth;if(a>992){size=Math.round(a/19.2)}else if(a<=992){size=Math.round(a/7.5);if(size>65){size=65}}else{size=100}document.documentElement.style.fontSize=size+'px'}
//function fontSize(){var size;var a = window.innerWidth;if (a <= 1600 && a > 992) {size = Math.round(a / 16)} else if (a <= 992) {size = Math.round(a/7.5);if (size > 65) {size = 65}} else {size = 100}document.documentElement.style.fontSize=size+'px'}
var scrollAction={x:"undefined",y:"undefined"},scrollDirection;function scrollFunc(){if(typeof scrollAction.x=="undefined"){scrollAction.x=window.pageXOffset;scrollAction.y=window.pageYOffset}var diffX=scrollAction.x-window.pageXOffset;var diffY=scrollAction.y-window.pageYOffset;if(diffX<0){scrollDirection="right"}else if(diffX>0){scrollDirection="left"}else if(diffY<0){scrollDirection="down"}else if(diffY>0){scrollDirection="up"}else{}scrollAction.x=window.pageXOffset;scrollAction.y=window.pageYOffset}window.onscroll=function(e){scrollFunc();if(scrollDirection=="down"){document.body.classList.add("scrollDown")}else if(scrollDirection=="up"){document.body.classList.remove("scrollDown")}};function domReady(fn){if(document.readyState==="complete"||document.readyState==="interactive"){setTimeout(fn,1)}else{if(document.addEventListener){document.addEventListener("DOMContentLoaded",fn,false)}else if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){fn()}});var top=false;try{top=window.frameElement==null&&document.documentElement}catch(e){}if(top&&top.doScroll){(function doScrollCheck(){try{top.doScroll("left");fn()}catch(e){setTimeout(doScrollCheck,50)}})()}}}}function init(){if(isIE()){var html=document.documentElement;ieFix(html,'iefix')}else{isIos()}if(detectIE()){var html=document.documentElement;var lang=(html.getAttribute('lang')||'').toLowerCase();var isChinese=lang=='zh-cn';var message=isChinese?'<div style="padding:20px;background:#fff8e6;border:1px solid #ffd700;font-family:Arial,sans-serif;text-align:center"><h2 style="color:#d80000;font-size:24px">\u60a8\u7684\u6d4f\u89c8\u5668\u5df2\u8fc7\u65f6</h2><p style="font-size:16px">\u60a8\u6b63\u5728\u4f7f\u7528internet explorer\u6d4f\u89c8\u5668\uff0c\u5fae\u8f6f\u5df2\u4e0d\u518d\u7ef4\u62a4\u6b64\u6d4f\u89c8\u5668\u3002</p><p style="font-size:16px">\u4e3a\u4e86\u83b7\u5f97\u66f4\u597d\u7684\u4f53\u9a8c\uff0c\u8bf7\u5347\u7ea7\u5230\u73b0\u4ee3\u6d4f\u89c8\u5668\uff1a</p><ul style="list-style:none;text-align:center;padding-left:0;font-size:16px"><li  style="display:inline"><a href="https://www.microsoft.com/edge" target="_blank" style="color:#0066cc;text-decoration:underline;">Microsoft Edge</a></li><li style="margin:0 30px;display:inline"><a href="https://www.google.cn/chrome/" target="_blank" style="color:#0066cc;text-decoration:underline;">Google Chrome</a></li><li style="display:inline"><a href="https://www.mozilla.org/firefox/" target="_blank" style="color:#0066cc;text-decoration:underline;">Mozilla Firefox</a></li></ul></div>':'<div style="padding:20px;background:#fff8e6;border:1px solid #ffd700;font-family:Arial,sans-serif;;text-align:center"><h2 style="color:#d80000;font-size:24px">Your browser is outdated</h2><p style="font-size:16px">You\'re using Internet Explorer which Microsoft no longer supports.</p><p style="font-size:16px">For better experience, please upgrade to modern browsers:</p><ul style="list-style:none;text-align:center;font-size:16px"><li style="display:inline"><a href="https://www.microsoft.com/edge" target="_blank" style="color:#0066cc;text-decoration:underline;">Microsoft Edge</a></li><li style="margin:0 30px;display:inline"><a href="https://www.google.cn/chrome/" target="_blank" style="color:#0066cc;text-decoration:underline;">Google Chrome</a></li><li style="display:inline"><a href="https://www.mozilla.org/firefox/" target="_blank" style="color:#0066cc;text-decoration:underline;">Mozilla Firefox</a></li></ul></div>';var body=document.getElementsByTagName('body')[0];body.innerHTML=message}}domReady(function(){init();fontSize()});

 /**
 * 横向滚动溢出隐藏导航自动滚动到可视区域函数
 * @param {string|jQuery} el - 容器元素选择器或jQuery对象
 * @param {boolean} isTab - 是否为选项卡模式(可点击切换)
 */
   function scNav(el,istab){
    $el = $(el);
    var $li = $el.find('li');
    var $selectedLi = $el.find('li.on');
     if ($selectedLi.length > 0) {
            var $ul = $el.find('ul');;
            var containerWidth = $el.width();
            var containerScrollLeft = $el.scrollLeft();
            var liPosition = $selectedLi.position().left;
            var liWidth = $selectedLi.outerWidth();
            var scrollTo = liPosition - (containerWidth / 2) + (liWidth / 2);
            $el.animate({scrollLeft: scrollTo}, 500);
             if(istab){
                $li.click(function() {
                $(this).addClass('on').siblings().removeClass('on');
                var $lis = $(this);
                var wrapperWidth = $el.width();
                var wrapperScrollLeft = $el.scrollLeft();
                var liPosition = $lis.position().left;
                var liWidth = $lis.outerWidth();
                var scrollTo = liPosition + wrapperScrollLeft - (wrapperWidth / 2) + (liWidth / 2);
                $el.stop().animate({scrollLeft: scrollTo}, 300);
            });
       }
     }
    
   }
 //应用
   scNav('.scNav',true)

//等比缩放
function fontSize(){
    var size;var a=window.innerWidth;if(a>992){size=Math.round(a/19.2)}else if(a<=992){size=Math.round(a/7.5);if(size>65){size=65}}else{size=100}$('html').css({'font-size':size+'px'});
} 
//正常缩放
function fontSize(){
var size;var a = window.innerWidth;
if (a <= 1600 && a > 992) {size = Math.round(a / 16)} else if (a <= 992) {size = Math.round(a/7.5);if (size > 65) {size = 65}} else {size = 100}$('html').css({'font-size': size + 'px'})  
}
//ie添加class
if(ieVer&&10>=ieVer||isIE11){$("html").addClass('ie11');}