沉迷于网络的人数

    科技2025-02-27  29

    沉迷于网络的人数

    Web性能暗示的生态系统很大(The ecosystem implied by the web performance is large)

    This is not a secret. Web performance is one of the most important goals of every web site whatever their kind : e-commerce, institutional, information… In fact, this is a shared goal by several profiles to satisfy the user :

    这不是秘密。 无论是哪种类型,Web性能都是每个网站的最重要目标之一:电子商务,机构,信息……实际上,这是多个配置文件满足用户的共同目标:

    Product owner : A web page must be loaded as quick as possible so that the users can start to interact with and turn into customers.

    产品负责人:必须尽快加载网页,以便用户可以开始与客户互动并转变为客户。

    SEO manager : A lightweight page helps to get better visibility in Search Engines such as Google, Bing…

    SEO经理:一个轻量级的页面有助于在Google,Bing等搜索引擎中获得更好的可见性。

    User : A web page takes too much time to load ? Well, the user doesn’t wait and visits the other competitors of the market.

    用户:网页加载时间太多? 好吧,用户不必等待,就可以拜访市场上的其他竞争对手。

    Support service : They really don’t want to receive users emails reporting the web site / app is unusable due to its heaviness.

    支持服务:他们真的不想接收用户的电子邮件,因为该网站/应用由于其笨重而无法使用。

    CTO : This is him which will be responsible in the sight of the CEO if the web page are too slow and they loose money.

    CTO :这是他,如果网页太慢并且放宽了资金,在首席执行官看来,他将负责。

    CEO : I don’t think he’s happy when competitor CEOs make fun of him telling how slow are his web site.

    首席执行官:当竞争对手的首席执行官嘲笑他说自己的网站运行速度很慢时,我认为他并不高兴。

    Web performance actors : They offer tools to measure the perfomance of the web page / app.

    网络性能参与者:他们提供工具来衡量网页/应用的性能。

    and the Front-End developer : He is the cornerstone between the previous profiles. He must make its best to make everybody happy.

    和前端开发人员:他是先前配置文件之间的基石。 他必须尽力使每个人都高兴。

    Web performance is so important in company strategy that they often make it a KPI (Key Performance Indicator) starting from the top of the hierarchy until the bottom (you, the front-end developer).

    Web性能在公司战略中是如此重要,以至于他们常常使它成为KPI(关键绩效指标),它从层次结构的顶部开始一直排到最底层(即前端开发人员)。

    让所有人都开心吧 (Let’s make everybody happy including you)

    延迟加载:减少加载时间的武器(Lazy-load : a weapon to reduce the load time)

    One of the best weapon to reduce the weight of web page is to only load what the user needs in the waterline of its screen. The other resources must be lazy-loaded on the fly when the user starts to interact in the web page by scrolling, clicking, writing something…

    减轻网页重量的最佳武器之一是仅将用户需要的内容加载到其屏幕的水线中。 当用户开始通过滚动,单击,编写某些内容在网页中进行交互时,其他资源必须实时进行延迟加载。

    Scroll lazy-loading is a little bit complex since you need to know when the target element is visible on the screen to load the related resources.

    滚动延迟加载有点复杂,因为您需要知道目标元素何时在屏幕上可见才能加载相关资源。

    动态导入与异步/等待 (Dynamic import with async/await)

    It’s easy to lazy-load resources from click, keyup, doubleclick… since the trigger function is the click event function itself. We just have to use 2 features :

    可以轻松地从单击,键入,双击中延迟加载资源,因为触发功能本身就是单击事件功能。 我们只需要使用2个功能:

    Thanks to Webpack and its code splitting feature, we can easily import a resource from a click. Event better, set a name to the output file by adding the comment webpackChunkName in the import function.

    借助Webpack及其代码拆分功能,我们可以轻松地从单击中导入资源。 如果情况更好,请通过在导入功能中添加注释webpackChunkName为输出文件设置名称。

    const buttonElement = document.querySelector('button'); buttonElement.addEventListener('click', async () => { const { default: Resource } = await import( /* webpackChunkName: "resource-name" */ 'resource-to-load' ); const resource = new Resource(); // Make something with the resource });

    I have a dream : element.addEventListener(‘visible’)

    我有一个梦想:element.addEventListener('visible')

    Load a resource when it becomes visible on the user screen has no magic event, it would be marvelous don’t you think ?

    当资源在用户屏幕上可见时加载资源时,没有任何魔术事件,这会很棒吗?

    交叉口观察者API (The Intersection Observer API)

    It is possible to know when an HTML Element is visible by adding a scroll event on it. But we have to make calculate the position on every scroll event and it is costly for the browser.

    通过在其上添加滚动事件,可以知道何时可见HTML元素。 但是我们必须计算每个滚动事件的位置,这对于浏览器来说是昂贵的。

    We have an other tool to do such and I’m pretty sure you already know it : this is the Intersection Observer API

    我们还有另一个工具可以做到这一点,我很确定您已经知道:这是Intersection Observer API

    The Intersection Observer API will help to provide us a trigger event when the target element is visible on the screen of the user.

    当目标元素在用户屏幕上可见时,Intersection Observer API将有助于向我们提供触发事件。

    If you website, app, should work on old browsers, think to add the related polyfill :

    如果您的网站(应用程序)应在旧的浏览器上运行,请考虑添加相关的polyfill:

    Have you already considered lazy-loading polyfill to avoid to load it in the browsers that already supports the feature ?

    您是否已经考虑过延迟加载polyfill以避免将其加载到已经支持该功能的浏览器中?

    So now we have all the ingredients to build a lazy-load util function

    所以现在我们具备了构建延迟加载util函数的所有要素

    延迟加载util函数(The lazy-load util function)

    The function is quite simple. Its goal is to provide us a event to know when to import on the fly the resources.

    功能很简单。 它的目标是为我们提供一个事件,以了解何时动态导入资源。

    export function onElementVisible( element: HTMLElement, // The element we want to know if it becomes visible options: IntersectionObserverInit = {} // Custom intersect observer options ): Promise<void> { // Default intersection observer const intersectionObserverOptions = { rootMargin: '0px', threshold: 0.3, ...options, }; //A promise resolved when the element becomes visible for the first time return new Promise(resolve => { const observer = new IntersectionObserver(async entries => { // We take the very first intersection entry const [entry] = entries; // Check wether the entry is intersecting the root or not if (entry.isIntersecting) { // Resolve the promise when it does resolve(); // Since we just want to observe once, disconnect the observer observer.disconnect(); } }, intersectionObserverOptions); observer.observe(element); }); }

    When you add this function you util file, lazy-load resources becomes a child’s play ! I assure you will get addicted to !

    当您将此功能添加到util文件时,延迟加载资源将成为孩子们的游戏! 我保证你会上瘾的!

    Let’s see a few examples of how to use it.

    让我们看一些使用它的例子。

    延迟加载图像 (Lazy-load images)

    import { onElementVisible } from '@/utils'; [...document.querySelectorAll('img.lazy')].forEach(async image => { await onElementVisible(image as HTMLElement); image.setAttribute('src', image.getAttribute('data-original') as string); });

    延迟加载库(Lazy-load library)

    Let’s imagine the product owner wants to add cross-sell slider section in the product pages . As a front-end developer, you choose or already use the library Swiper. Well this library is rather heavy and you want to lazy-load it.

    假设产品所有者想要在产品页面中添加交叉销售滑块部分。 作为前端开发人员,您选择或已经使用了Swiper库。 好吧,这个库很重,您想延迟加载它。

    import { onElementVisible } from '@/utils'; const crossSellElement = document.getElementById('section-product-cross-sell') as HTMLElement; onElementVisible(crossSellElement).then(async () => { // Load the swiper library const { default: Swiper } = await import(/* webpackChunkName: "swiper" */ 'swiper'); // Instanciate Swiper new Swiper(crossSellElement.querySelector('.swiper-container') as HTMLElement); });

    延迟加载JS框架(Lazy-load JS Framework)

    Yes, you can also load a JS Framework on the fly if you use in a part of your page. Let’s imagine you add a newsletter sign-in feature built with a JS Framework (VueJS, React…) :

    是的,如果您在页面的一部分中使用JS,也可以动态加载JS框架。 假设您添加了一个使用JS框架(VueJS,React…)构建的新闻通讯登录功能:

    With VueJS

    使用VueJS

    import { onElementVisible } from '@/utils'; const newsletterSignUpElement = document.querySelector('.newsletter-signup-form'); onElementVisible(newsletterSignUpElement).then(async () => { const { default: Vue } = await import(/* webpackChunkName: "vue" */ 'vue'); new Vue({ template: '<NewsletterSignup />', components: { NewsletterSignUp: () => import( /* webpackChunkName: "newsletter-signup" */ '@/components/NewsletterSignup.vue' ), }, }).$mount(newsletterSignUpElement); })

    With React

    使用React

    import { onElementVisible } from '@/utils'; const newsletterSignUpElement = document.querySelector('.newsletter-signup-form'); onElementVisible(newsletterSignUpElement).then(async () => { const { lazy } = await import(/* webpackChunkName: "react" */ 'react'); const { default: ReactDOM } = await import(/* webpackChunkName: "react-dom" */ 'react-dom'); const NewsletterSignup = lazy(() => import("./NewsletterSignup")); ReactDOM.render(<NewsletterSignup />, newsletterSignUpElement); })

    进一步深入的技巧(Tips to go deeper)

    To use more efficiently the lazy-load function, here are some tips or piece of advice I give you.

    为了更有效地使用延迟加载功能,以下是我给您的一些提示或建议。

    Display a fallback content to indicate your users a content is about to be displayed

    显示后备内容以指示您的用户内容将要显示

    Set the expected dimension to the target DOM element to avoid clipping

    将预期尺寸设置为目标DOM元素以避免裁剪

    Check the output files in your favorite browser in network section to see how many bytes you saved from the initial web page loading

    在您喜欢的网络浏览器部分中检查输出文件,以查看从初始网页加载中保存的字节数

    Use the coverage browser tool to identify heavy resources that can be lazy-loaded

    使用coverage浏览器工具来确定可以延迟加载的大量资源

    结论(Conclusion)

    Web performance should be always considered in the new features the product owner is conceiving in interaction with the front-end developer and the UX/UI team. The idea is to offer the smoother UI as possible and to hide the features complexity to the users. That’s why I think util function like that will help you reach this goal.

    产品所有者在与前端开发人员和UX / UI团队进行交互时所构想的新功能中,应始终考虑Web性能。 这个想法是要提供尽可能平滑的UI,并向用户隐藏功能的复杂性。 这就是为什么我认为这样的util函数可以帮助您实现此目标的原因。

    翻译自: https://medium.com/javascript-in-plain-english/a-lazy-load-util-function-you-will-get-addicted-to-e682ab410ac8

    沉迷于网络的人数

    Processed: 0.015, SQL: 8