الأداء والنشر

ملخص المستوى · الأداء والنشر · المستوى 1

البناء والسرعة

كل ما تعلّمته في هذا المستوى، درسًا بدرس: الفكرة، والكود، وما يظهر عند تشغيله. اقرأه قبل الاختبار، أو احتفظ به ملف PDF.

ما يعلّمه هذا المستوى: اكتب البناء الذي يجعل الموقع صغيرًا وسريعًا، وتحقّق منه مقابل ميزانية للسرعة.

10 دروساختبار المستوى

  1. 1مجلد البناء

    انسخ الموقع إلى dist، من جديد في كل مرة.

    الفكرة

    التذكرة CL-501 من قائد فريق الويب: ملفات واجهة المتجر موجودة في src/. الخادم المستضيف لا يقدّم إلا ما في dist/، لذلك يبدأ كل إصدار ببناء يملأ dist/.

    البناء يقرأ مجلد المصدر ويكتب مجلد الناتج. fs.readdirSync("src") تعرض الأسماء الموجودة في مجلد، وfs.copyFileSync(from, to) تنسخ ملفًا واحدًا، وpath.join("src", name) تبني المسار.

    الكود

    const fs = require("fs");
    const path = require("path");
    fs.rmSync("dist", { recursive: true, force: true });
    fs.mkdirSync("dist");
    const names = fs.readdirSync("src");
    for (const name of names) {
      fs.copyFileSync(path.join("src", name), path.join("dist", name));
    }
    console.log("Built " + names.length + " files");

    ما يظهر

    PASS Every file in src is copied into dist
  2. 2مجلدات داخل مجلدات

    انسخ شجرة مجلدات كاملة.

    الفكرة

    التذكرة CL-502: انتقلت الصور إلى src/images/ والأيقونات إلى src/images/icons/. البناء ينسخ الملفات العليا فقط، لذلك لا تظهر أي صور في الصفحات المنشورة.

    fs.readdirSync(dir, { withFileTypes: true }) تعطي مدخلًا واحدًا لكل اسم، وentry.isDirectory() تميّز المجلد من الملف. الدالة التي تستدعي نفسها لكل مجلد تمرّ على الشجرة كلها: انسخ الملف، أو أنشئ المجلد في dist وادخل إليه.

    الكود

    const fs = require("fs");
    const path = require("path");
    function copyDir(from, to) {
      fs.mkdirSync(to, { recursive: true });
      let count = 0;
      for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
        const a = path.join(from, entry.name);
        const b = path.join(to, entry.name);
        if (entry.isDirectory()) {
          count += copyDir(a, b);
        } else {
          fs.copyFileSync(a, b);
          count++;
        }
      }
      return count;
    }
    fs.rmSync("dist", { recursive: true, force: true });
    …

    ما يظهر

    PASS Files in folders inside folders are copied
  3. 3CSS أصغر

    احذف ما لا يحتاجه المتصفح.

    الفكرة

    التذكرة CL-503: يقول تقرير السرعة إن style.css يُرسَل بكل تعليقاته وفواصل أسطره ومسافاته. المتصفحات لا تحتاج إلى أي منها، لكن كل زائر يحمّلها.

    التصغير يحذف التعليقات /* … */، وفواصل الأسطر، والمسافات حول { } : ; ,. تعبير نمطي (regular expression) ينفّذ كل خطوة: css.replace(/\/\*[\s\S]*?\*\//g, "") يحذف التعليقات.

    الكود

    const fs = require("fs");
    function minify(css) {
      return css
        .replace(/\/\*[\s\S]*?\*\//g, "")
        .replace(/\s+/g, " ")
        .replace(/\s*([{}:;,])\s*/g, "$1")
        .trim();
    }
    const css = fs.readFileSync("src/style.css", "utf8");
    const small = minify(css);
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync("dist/style.css", small);
    console.log("style.css: " + Buffer.byteLength(css) + " bytes, now " + Buffer.byteLength(small) + " bytes");

    ما يظهر

    PASS minify removes the comments and line breaks and keeps every rule
  4. 4أسماء ملفات تتغير مع المحتوى

    النسخة الجديدة تحصل على اسم جديد.

    الفكرة

    التذكرة CL-504: بعد كل إصدار يظل بعض العملاء يحصلون على app.js القديم من التخزين المؤقت (cache) في متصفحهم، فتتعطل الصفحة.

    أعطِ كل ملف اسمًا مأخوذًا من محتواه: app.3f9a1c2e.js. النسخة الجديدة تحصل على اسم جديد، فلا يستطيع أي متصفح استخدام نسخة قديمة، ويستطيع الخادم المستضيف أن يطلب من المتصفحات الاحتفاظ بهذه الملفات لمدة سنة.

    الكود

    const fs = require("fs");
    const path = require("path");
    const crypto = require("crypto");
    function hashName(file, text) {
      const hash = crypto.createHash("sha256").update(text).digest("hex").slice(0, 8);
      const ext = path.extname(file);
      return path.basename(file, ext) + "." + hash + ext;
    }
    const js = fs.readFileSync("src/app.js", "utf8");
    const name = hashName("app.js", js);
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync(path.join("dist", name), js);
    const html = fs.readFileSync("src/index.html", "utf8");
    fs.writeFileSync("dist/index.html", html.replace('src="app.js"', 'src="' + name + '"'));
    console.log("app.js -> " + name);

    ما يظهر

    PASS hashName puts 8 characters of the content's sha256 in the name
  5. 5مقاسات الصور

    احجز مساحة كل صورة قبل وصولها.

    الفكرة

    التذكرة CL-505: صفحة المنتج تقفز أثناء التحميل: ينزل النص إلى الأسفل في كل مرة تصل فيها صورة. يسمّي تقرير السرعة هذا إزاحة التخطيط (layout shift).

    عندما يكون لـ <img> السمتان width وheight، يحجز المتصفح المساحة الصحيحة لها قبل وصول الصورة، فلا يقفز شيء. مقاس كل صورة موجود في images.json، مثل { "hero.jpg": { "width": 1600, "height": 900 } }.

    الكود

    const fs = require("fs");
    function addSizes(html, sizes) {
      return html.replace(/<img [^>]*>/g, (tag) => {
        const m = /src="images\/([^"]+)"/.exec(tag);
        const size = m && sizes[m[1]];
        if (!size || /\swidth=/.test(tag)) return tag;
        return tag.replace("<img ", '<img width="' + size.width + '" height="' + size.height + '" ');
      });
    }
    const html = fs.readFileSync("src/index.html", "utf8");
    const sizes = JSON.parse(fs.readFileSync("images.json", "utf8"));
    const out = addSizes(html, sizes);
    const count = (s) => (s.match(/<img [^>]*width=/g) || []).length;
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync("dist/index.html", out);
    console.log("Sizes added to " + (count(out) - count(html)) + " pictures");

    ما يظهر

    PASS Each img gets the width and height from images.json
  6. 6حمّل الصور عند الحاجة إليها

    الصور البعيدة في أسفل الصفحة تنتظر التمرير.

    الفكرة

    التذكرة CL-506: صفحة الكتالوج تحمّل كل صور المنتجات دفعة واحدة، حتى البعيدة في أسفل الصفحة التي لا يصل إليها معظم الزوار.

    loading="lazy" على <img> يطلب من المتصفح ألا يحمّل الصورة إلا عندما يقترب منها الزائر بالتمرير. لا تضعها على الصورة الأولى، الصورة الكبيرة في الأعلى: فهي تُرى فورًا ويجب أن تُحمَّل أولًا.

    الكود

    const fs = require("fs");
    function lazyImages(html) {
      let seen = 0;
      return html.replace(/<img [^>]*>/g, (tag) => {
        seen++;
        if (seen === 1 || /\sloading=/.test(tag)) return tag;
        return tag.replace("<img ", '<img loading="lazy" decoding="async" ');
      });
    }
    const out = lazyImages(fs.readFileSync("src/index.html", "utf8"));
    const all = (out.match(/<img /g) || []).length;
    const lazy = (out.match(/loading="lazy"/g) || []).length;
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync("dist/index.html", out);
    console.log("Lazy loading on " + lazy + " of " + all + " pictures");

    ما يظهر

    PASS Every picture after the first has loading="lazy" and decoding="async"
  7. 7سكربتات لا تعطّل الصفحة

    يسمح defer للصفحة بأن تُرسم أولًا.

    الفكرة

    التذكرة CL-507: على الهواتف تبقى الصفحة بيضاء لثانية قبل أن يظهر أي شيء. يقول تقرير السرعة: render-blocking script in head.

    وسم <script src> داخل <head> يوقف المتصفح: فهو يحمّل السكربت وينفّذه قبل أن يرسم أي شيء. مع defer، يُحمَّل السكربت أثناء رسم الصفحة ويُنفَّذ بعد قراءة الصفحة، بالترتيب نفسه كما من قبل.

    الكود

    const fs = require("fs");
    function deferScripts(html) {
      const end = html.indexOf("</head>");
      const head = html.slice(0, end).replace(/<script [^>]*>/g, (tag) => {
        if (!/\ssrc=/.test(tag) || /\s(defer|async)[\s>=]/.test(tag) || /type="module"/.test(tag)) return tag;
        return tag.replace("<script ", "<script defer ");
      });
      return head + html.slice(end);
    }
    const html = fs.readFileSync("src/index.html", "utf8");
    const out = deferScripts(html);
    const count = (s) => (s.match(/<script defer /g) || []).length;
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync("dist/index.html", out);
    console.log("Scripts deferred: " + (count(out) - count(html)));

    ما يظهر

    PASS Plain scripts in the head get defer
  8. 8خطوط بلا انتظار

    اعرض النص فورًا، واجلب الخط مبكرًا.

    الفكرة

    التذكرة CL-508: على هاتف بطيء تبقى العناوين غير مرئية لمدة 3 ثوانٍ، ثم يظهر الخط دفعة واحدة.

    افتراضيًا يخفي المتصفح النص حتى يصل خط الويب الخاص به. font-display: swap; في قاعدة @font-face يعرض النص فورًا بخط النظام، ثم يبدّله إلى خط الويب عندما يجهز.

    الكود

    const fs = require("fs");
    function swapFonts(css) {
      return css.replace(/@font-face\s*{([^}]*)}/g, (rule, body) => {
        if (/font-display/.test(body)) return rule;
        return "@font-face {" + body.replace(/\s*$/, "") + "\n  font-display: swap;\n}";
      });
    }
    const css = fs.readFileSync("src/style.css", "utf8");
    const fonts = [];
    for (const file of css.match(/fonts\/[\w.-]+\.woff2/g) || []) {
      if (!fonts.includes(file)) fonts.push(file);
    }
    const links = fonts.map((f) => '<link rel="preload" href="' + f + '" as="font" type="font/woff2" crossorigin>\n').join("");
    const html = fs.readFileSync("src/index.html", "utf8").replace("</head>", links + "</head>");
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync("dist/style.css", swapFonts(css));
    fs.writeFileSync("dist/index.html", html);
    console.log("Preloaded " + fonts.length + " fonts");

    ما يظهر

    PASS Each @font-face without font-display gets font-display: swap
  9. 9ترويسات التخزين المؤقت

    أخبر المتصفحات بما يمكنها الاحتفاظ به، ولأي مدة.

    الفكرة

    التذكرة CL-509: الخادم المستضيف الخاص بالمتجر يقدّم dist/. الملفات ذات الأسماء المشفّرة بالبصمة لا تتغير أبدًا، لذلك يمكن للمتصفحات الاحتفاظ بها. أما index.html فيتغير مع كل إصدار، لذلك يجب أن تتحقق منه المتصفحات في كل مرة.

    ترويسة Cache-Control تحدد المدة التي يمكن للمتصفح أن يحتفظ فيها بالملف. public, max-age=31536000, immutable تعني سنة، دون أن يسأل مرة أخرى: وهذا مناسب للأسماء المشفّرة بالبصمة مثل app.3f9a1c2e.js (نقطة، ثم 8 أحرف من 0-9 وa-f، ثم الامتداد). no-cache تعني احتفظ به، لكن اسأل الخادم في كل مرة هل تغيّر: وهذا مناسب لـ HTML. public, max-age=3600 (ساعة) تناسب الملفات الأخرى.

    الكود

    const http = require("http");
    const fs = require("fs");
    const path = require("path");
    const TYPES = { ".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "text/javascript", ".jpg": "image/jpeg", ".png": "image/png", ".svg": "image/svg+xml", ".woff2": "font/woff2" };
    function cacheFor(file) {
      if (file.endsWith(".html")) return "no-cache";
      if (/\.[0-9a-f]{8}\.\w+$/.test(file)) return "public, max-age=31536000, immutable";
      return "public, max-age=3600";
    }
    const server = http.createServer((req, res) => {
      const url = req.url.split("?")[0];
      const file = path.join("dist", url === "/" ? "index.html" : url);
      if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) {
        res.writeHead(404, { "Content-Type": "text/plain" });
        res.end("Not found");
        return;
      }
      res.writeHead(200, { "Content-Type": TYPES[path.extname(file)] || "application/octet-stream", "Cache-Control": cacheFor(file) });
    …

    ما يظهر

    PASS Each file comes back with its content and its Content-Type
  10. 10ميزانية السرعة

    الإصدار الثقيل أكثر من اللازم لا يُنشر.

    الفكرة

    التذكرة CL-510: اتفق الفريق على ميزانية لواجهة المتجر: يبقى JavaScript أقل من 170 KB، وCSS أقل من 50 KB، والصور أقل من 900 KB. أي إصدار يتجاوزها يجب أن يتوقف قبل نشره.

    ميزانية السرعة تحوّل عبارة «الموقع يبدو بطيئًا» إلى أرقام يستطيع البناء التحقق منها. يحتوي budget.json على حد بالبايت لكل نوع من الملفات، مثل { "js": 170000, "css": 50000, "images": 900000 }. fs.statSync(file).size هو حجم الملف بالبايت.

    الكود

    const fs = require("fs");
    const path = require("path");
    const budget = JSON.parse(fs.readFileSync("budget.json", "utf8"));
    const KIND = { ".js": "js", ".css": "css", ".jpg": "images", ".png": "images", ".svg": "images", ".webp": "images" };
    const totals = {};
    function walk(dir) {
      for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
        const file = path.join(dir, entry.name);
        if (entry.isDirectory()) {
          walk(file);
        } else {
          const kind = KIND[path.extname(file)];
          if (kind) totals[kind] = (totals[kind] || 0) + fs.statSync(file).size;
        }
      }
    }
    walk("dist");
    let over = false;
    …

    ما يظهر

    PASS Each kind's line shows the total of its files, in folders too

هل أنت مستعد للاختبار؟ اختبار المستوى مهمة حقيقية واحدة تستخدم ما يغطيه هذا الملخص.

ابدأ اختبار المستوى