Html

Outils principaux

Les outils de développement peuvent être ouverts avec Ctrl + Shift + I ou F12 sous Windows et Linux, et Cmd + Opt + I sous macOS.

La partie droite de la barre d’outils contient plusieurs boutons qui permettent d’effectuer des actions, ou de changer certaines options des outils.

Ce bouton apparait lorsqu’il y a plusieurs iframe dans la page. Cliquer dessus affiche la liste des iframes sur la page actuelle, et permet de sélectionner celle ciblée par les outils.
Ce bouton permet de prendre une capture d’écran de la page. (Note: Cette fonctionnalité n’est pas activée par défaut, et doit être activée dans les paramètres avant).
Active le mode Vue Adaptative.
Ouvre le menu qui inclut les options d’ancrage, la possibilités d’activer la console scindée, et d’afficher les options des outils de développement. Ce menu inclut également des liens vers la documentation des outils de développement de Firefox et vers la communauté Mozilla.
Ferme les outils de développement.

Inspecteur

Permet de voir et modifier une page en HTML et en CSS. Permet de visualiser différents aspects de la page y compris les animations, l’agencement de la grille.

Inspecteur d’Accessibilité

Permet d’examiner l’arborescence d’accessibilité de la page courante, qui est utilisée par les lecteurs d’écran et d’autres technologies d’assistance, afin de pouvoir savoir ce qui manque ou ce qui peut être amélioré.

Модули

Данный раздел содержит модули, которые расположены в порядке, наиболее оптимальном для их изучения. Вам определённо следует начать с первого модуля.

Введение в HTML
Этот модуль дает основу, которая позволит вам использовать важные понятия и синтаксис, вы рассмотрите применение HTML к тексту, узнаете как создать гиперссылки и как использовать HTML для структурирования веб-страницы.
Мультимедиа и встраивание
В этом модуле рассматривается использование HTML для подключения мультимедиа-контента к вашим веб-страницам, включая различные способы встраивания изображений, видео и аудио и даже других веб-страниц.
HTML Таблицы
Представление табличных данных на веб-странице в понятном, доступном образе, может стать проблемой. Этот модуль описывает основы табличной разметки, а также более сложные функции, такие как реализация подписок и резюме.
HTML Формы
Формы — очень важная часть интернета, они  обеспечивают  большую часть функциональных возможностей, необходимых для взаимодействия с веб-сайтом, например, регистрация и вход в систему, отправка отзывов, покупка продуктов и многое другое. В этом модуле вы начнете с создания частей форм на стороне клиента.

Руководства для начинающих

Наше Пространство изучения HTML содержит множество модулей, которые обучают HTML с нуля — начальные знания не требуются.

Введение в HTML
Этот модуль закладывает основу, знакомя вас с важными понятиями и синтаксисом, такими как применение HTML к тексту, создание гиперссылок и использование HTML для построения веб-страницы.
Мультимедиа и встраивание
В этом модуле рассматривается, как использовать HTML для добавления мультимедиа на ваши веб-страницы, включая различные способы вставки изображений, а также для встраивания видео, аудио, и даже других веб-страниц целиком.
HTML-таблицы
Представление табличных данных на веб-странице в понятной, доступной форме может быть проблемой

Этот модуль охватывает базовую разметку таблиц, а также более сложные особенности, такие как добавление заголовков и описаний.
HTML-формы
Формы являются очень важной частью Веба — они предоставляют большую часть функционала, необходимого для взаимодействия с веб-сайтами, например регистрация и вход в систему, отправка отзывов, покупка товаров, и многое другое. Этот модуль познакомит вас с созданием клиентских (client-side/front-end) частей форм.
Используйте HTML для решения распространенных задач.
Содержит ссылки на разделы, объясняющие как использовать HTML для решения самых распространенных задач при создании веб-страницы: работа с заголовками, добавление изображений или видео, выделение контента, создание простой формы и т.д.

Step 3 – A Simple Example

Let’s put it all together with a simple HTTP request. Our JavaScript will request an HTML document, , which contains the text «I’m a test.» Then we’ll the contents of the response. Note that this example uses vanilla JavaScript — no jQuery is involved. Also, the HTML, XML and PHP files should be placed in the same directory.

<button id="ajaxButton" type="button">Make a request</button>

<script>
(function() {
  var httpRequest;
  document.getElementById("ajaxButton").addEventListener('click', makeRequest);

  function makeRequest() {
    httpRequest = new XMLHttpRequest();

    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }
    httpRequest.onreadystatechange = alertContents;
    httpRequest.open('GET', 'test.html');
    httpRequest.send();
  }

  function alertContents() {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        alert(httpRequest.responseText);
      } else {
        alert('There was a problem with the request.');
      }
    }
  }
})();
</script>

In this example:

  • The user clicks the «Make a request» button;
  • The event handler calls the function;
  • The request is made and then () the execution is passed to ;
  • checks if the response was received and OK, then s the contents of the file.

Note: If you’re sending a request to a piece of code that will return XML, rather than a static HTML file, you must set response headers to work in Internet Explorer. If you do not set header , IE will throw a JavaScript «Object Expected» error after the line where you tried to access an XML element.

Note 2: If you do not set header the browser will cache the response and never re-submit the request, making debugging challenging. You can also add an always-different GET parameter, like a timestamp or random number (see )

Note 3: If the variable is used globally, competing functions calling can overwrite each other, causing a race condition. Declaring the variable local to a closure containing the AJAX functions avoids this.

In the event of a communication error (such as the server going down), an exception will be thrown in the method when accessing the response status. To mitigate this problem, you could wrap your statement in a :

function alertContents() {
  try {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        alert(httpRequest.responseText);
      } else {
        alert('There was a problem with the request.');
      }
    }
  }
  catch( e ) {
    alert('Caught Exception: ' + e.description);
  }
}

ウェブ技術

基礎技術

HTML
HTML (HyperText Markup Language; ハイパーテキストマークアップ言語) はウェブページのコンテンツを記述や定義するための言語です。
CSS
CSS (Cascading Style Sheets; カスケーディングスタイルシート) はウェブコンテンツの見た目や表現を制御するために使います。
HTTP
HTTP (Hypertext Transfer Protocol) は HTML その他のハイパーメディア文書をウェブで配信するために使われます。

スクリプト

JavaScript
JavaScript はブラウザー内で動作するプログラミング言語で、対話的、動的機能をもつウェブサイトやアプリケーションを作るのに使われます。
Node.js の出現により、JavaScript をサーバーでも実行できます。
Web API
Web API (Web Application Programming Interfaces) はいろいろなタスクを実行するのに使われます。そのタスクには DOM の操作や、音声や動画の再生や、三次元グラフィックの生成があります。

  • Web API インターフェイスリファレンス — ウェブ開発で使うことのできるすべてのオブジェクトを載せています。
  • WebAPI ページでは、通信やハードウェアアクセスや、その他のウェブアプリケーション開発用のすべての API を載せています。
  • イベントリファレンス ではウェブページやアプリケーションの中で行われる関心事項を監視して反応するのに使うすべてのイベントを載せています。
Web component
Web Component は、再利用可能なカスタム要素を作成することができる技術の集合体です。機能を実現はコードから隠蔽することができ、ウェブアプリの中で利用することができます。

グラフィック

Canvas
要素は JavaScript を使って 2次元のグラフィック描画できる API を提供します。
SVG
SVG (Scalable Vector Graphics) では直線、曲線、その他の幾何学形状を使ってグラフィックを描画します。ベクターにて、いかなるサイズでも明瞭に拡大縮小される画像を作成できます。
WebGL
WebGL は HTML5 の 要素を用いて 3D や 2D のグラフィックを描画できる JavaScript API です。この技術ではウェブコンテンツの中で標準の OpenGL ES を使えます。

音声、動画、マルチメディア

ウェブメディア技術
メディア関連の API 一覧で、それぞれ必要となる文書へのリンクがあります。
Media capture and streams API
ストリーミング、録画、メディア操作をローカル/ネットワーク経由の両方で可能にする API のリファレンスです。ここには動画やオーディオや静止画をキャプチャーするためのローカルのカメラやマイクを使うものも入っています。
HTML の音声と動画の使用
動画や音声をウェブページに組み込んで再生を管理します。
WebRTC
WebRTC での RTC とは Real-Time Communications を表し、これはオーディオ/ビデオのストリーミングとデータ共有を、ブラウザーのクライアント同士 (ピアー) で可能にするテクノロジーです。

Step 5 – Working with data

Finally, let’s send some data to the server and receive a response. Our JavaScript will request a dynamic page this time, , which will take the data we send and return a «computed» string — «Hello, !» — which we’ll

First we’ll add a text box to our HTML so the user can enter their name:

<label>Your name: 
  <input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
  Make a request
</span>

We’ll also add a line to our event handler to get the user’s data from the text box and send it to the function along with the URL of our server-side script:

  document.getElementById("ajaxButton").onclick = function() { 
      var userName = document.getElementById("ajaxTextbox").value;
      makeRequest('test.php',userName); 
  };

We need to modify to accept the user data and pass it along to the server. We’ll change the request method from to , and include our data as a parameter in the call to :

  function makeRequest(url, userName) {

    ...

    httpRequest.onreadystatechange = alertContents;
    httpRequest.open('POST', url);
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    httpRequest.send('userName=' + encodeURIComponent(userName));
  }

The function can be written the same way it was in Step 3 to alert our computed string, if that’s all the server returns. However, let’s say the server is going to return both the computed string and the original user data. So if our user typed «Jane» in the text box, the server’s response would look like this:

To use this data within , we can’t just alert the , we have to parse it and alert , the property we want:

function alertContents() {
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    if (httpRequest.status === 200) {
      var response = JSON.parse(httpRequest.responseText);
      alert(response.computedString);
    } else {
      alert('There was a problem with the request.');
    }
  }
}

The file should contain the following:

For more on DOM methods, be sure to check out Document Object Model (DOM).

Возможные типы задач

Есть несколько направлений, которые Вы можете выбрать, чтобы внести свой вклад в развитие MDN, в зависимости от квалификации и интересов. Даже если некоторые задачи покажутся сложными, у нас есть много других, простых и доступных. На решение большинства из них уйдет не более пяти минут (а то и меньше!). Рядом с задачей и ее кратким описанием Вы найдете приблизительное время, за которое обычно решаются задачи данного типа.

Вариант 1: Мне нравятся слова

Вы можете помочь нам проверить или отредактировать существующие документы, указать правильные тэги или поправить их.

  • Напишите описание страницы (5-15 минут)
  • Редакционная проверка (5–30 минут)
  • Добавьте новую запись в словарь (15 минут — 1 час)
  •  (1-3 часа)

Вариант 3: Мне одинаково нравится писать слова и код

У нас есть задачи, которые требуют технических навыков и языковых, такие как написание новых статей, технический обзор, а также адаптация документов.

  • (5 минут)
  • Техническая проверка (30 минут)

Вариант 4: Я хочу перевести MDN на свой язык

Вся работа по локализации и переводу MDN делается нашим замечательным сообществом добровольцев.

  • Связь с другими локализаторами, перечисленными в локализации проектов (30 минут)

Вариант 5: Я нашел ошибки, но не знаю, как их исправить

Вы можете сообщить нам о найденых ошибках. (5 минут)

Используйте следующие данные при отправке:

Поле в трекере Bugzilla Значение
Документация для разработчиков
Страница, где была найдена ошибка
По возможности, напишите, что Вам известно о проблеме и где найти корректную информацию. Это может быть человек или ссылки на веб-сайты с правильной информацией.

Подключение инструментов разработчика

Если вы откроете инструменты разработчика с помощью или аналогичных пунктов меню, они будут нацелены на документ, размещенный на текущей активной вкладке. Но вы также можете прикрепить инструменты к множеству других целей, как в текущем браузере, так и в разных браузерах или даже на разных устройствах.

about:debugging
Отладка надстроек, вкладок контента и рабочих, работающих в браузере.
Подключение к Firefox для Android
Подключите инструменты разработчика к Firefox, работающему на устройстве Android.
Подключение к iframes
Подключите инструменты разработчика к конкретному iframe на текущей странице.
Подключите инструменты разработчика к Chrome на Android и Safari на iOS.

Step 2 – Handling the server response

When you sent the request, you provided the name of a JavaScript function to handle the response:

httpRequest.onreadystatechange = nameOfTheFunction;

What should this function do? First, the function needs to check the request’s state. If the state has the value of (corresponding to 4), that means that the full server response was received and it’s OK for you to continue processing it.

if (httpRequest.readyState === XMLHttpRequest.DONE) {
    // Everything is good, the response was received.
} else {
    // Not ready yet.
}

The full list of the values is documented at XMLHTTPRequest.readyState and is as follows:

  • 0 (uninitialized) or (request not initialized)
  • 1 (loading) or (server connection established)
  • 2 (loaded) or (request received)
  • 3 (interactive) or (processing request)
  • 4 (complete) or (request finished and response is ready)

Next, check the HTTP response status codes of the HTTP response. The possible codes are listed at the W3C. In the following example, we differentiate between a successful and unsuccessful AJAX call by checking for a response code.

if (httpRequest.status === 200) {
    // Perfect!
} else {
    // There was a problem with the request.
    // For example, the response may have a 404 (Not Found)
    // or 500 (Internal Server Error) response code.
}

After checking the state of the request and the HTTP status code of the response, you can do whatever you want with the data the server sent. You have two options to access that data:

  • – returns the server response as a string of text
  • – returns the response as an object you can traverse with JavaScript DOM functions

Note that the steps above are valid only if you used an asynchronous request (the third parameter of was unspecified or set to ). If you used a synchronous request you don’t need to specify a function, but this is highly discouraged as it makes for an awful user experience.

Веб-технологии

Основы веб разработки

HTML
Язык гипертекстовой разметки — это язык, используемый для определения структуры и описания содержания веб-страницы в структурированной форме.
CSS
Каскадные таблицы стилей используются для описания внешнего вида веб-контента.
HTTP
HyperText Transfer Protocol (HTTP) — это протокол, по которому доставляются HTML и прочие медиа-документы.

Написание сценариев

JavaScript
JavaScript — язык программирования, широко используемый для реализации взаимодействия пользователя с веб-сайтами и приложениями.
Веб API
Данный раздел включает справочные материалы по каждому из отдельно взятых API, содержащих огромные возможности для создания веб-сценариев, включая DOM и все связанные с ним API, которые вы можете использовать для построения веб-контента и приложений.

  • Справочник по веб API содержит все интерфейсы в алфавитном порядке.
  • Справка по событиям содержит список событий, которые возникают на веб-странице или в веб-приложении.
Веб Компоненты
Веб Компоненты — это набор различных технологий, позволяющих создавать собственные переиспользуемые элементы — со своей функциональностью, инкапсулированной от остального кода — и использовать их в ваших веб-приложениях.

Графика

Canvas
элемент предоставляет API для рисования 2D-графики, с использованием JavaScript.
SVG
SVG (Scalable Vector Graphics — масштабируемая векторная графика) —   позволяет вам описать изображение в виде линий, кривых и других геометрических фигур. Благодаря этому можно машстабировать рисунок без потери качества.
WebGL
WebGL — это JavaScript API,  позволяющее рисовать 3D или 2D изображения используя  HTML элемент . Эта технология позволяет использовать стандарт OpenGL ES в Web-содержимом.

Web медиа-технологии
Список связанного с медиа API, со ссылками на документацию для каждого из них.
Media capture and streams API
Справочник для API, используемого для потоковой передачи, записи и управления данным как локально, так и по сети. Также включает в себя инструменты для использования локальных камер и микрофонов для захвата видео, аудио и статичных изображений.
Использование HTML аудио и видео
Включение видео и\или аудио в веб-страницу и управление их воспроизведением.
WebRTC
RTC в WebRTC означает Real-Time Communications (связь в реальном времени) — технологию, обеспечивающую поток аудио или видео и обмен данным между одноранговыми клиентами браузера.

Основные достоинства «Файрфокс Девелопер Эдишн»

Помимо вышесказанного, пользователями также отмечены такие достоинства, как:

  • стандартизированный и приемлемый период выхода обновлений браузера. Если вас не устраивают еженедельные патчи, всегда можно поучаствовать в бета-тесте «ночных» версий;
  • небольшой «вес». В отличие от других профессиональных инструментов, «Файрфокс» для разработчиков остается браузером и не занимает много места на ПК или флешке.

Заключение

Если вас устраивает всё отмеченное выше, то вы в любой момент можете скачать и опробовать браузер и самостоятельно решить, подходит ли он для ваших целей.

Рекомендуем!
InstallPack
Стандартный установщик
Официальный дистрибутив Firefox
Тихая установка без диалоговых окон
Рекомендации по установке необходимых программ
Пакетная установка нескольких программ

Step 1 – How to make an HTTP request

In order to make an HTTP request to the server with JavaScript, you need an instance of an object with the necessary functionality. This is where comes in. Its predecessor originated in Internet Explorer as an ActiveX object called . Then, Mozilla, Safari, and other browsers followed, implementing an object that supported the methods and properties of Microsoft’s original ActiveX object. Meanwhile, Microsoft implemented XMLHttpRequest as well.

// Old compatibility code, no longer needed.
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

Note: For illustration purposes, the above is a somewhat simplified version of the code to be used for creating an XMLHttp instance. For a more realistic example, see step 3 of this article.

After making a request, you will receive a response back. At this stage, you need to tell the XMLHttp request object which JavaScript function will handle the response, by setting the property of the object and naming it after the function to call when the request changes state, like this:

Note that there are no parentheses or parameters after the function name, because you’re assigning a reference to the function, rather than actually calling it. Alternatively, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called «anonymous functions») to define the actions that will process the response, like this:

httpRequest.onreadystatechange = function(){
    // Process the server response here.
};

Next, after declaring what happens when you receive the response, you need to actually make the request, by calling the and methods of the HTTP request object, like this:

httpRequest.open('GET', 'http://www.example.org/some.file', true);
httpRequest.send();
  • The first parameter of the call to is the HTTP request method – GET, POST, HEAD, or another method supported by your server. Keep the method all-capitals as per the HTTP standard, otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods, check the W3C specs.
  • The second parameter is the URL you’re sending the request to. As a security feature, you cannot call URLs on 3rd-party domains by default. Be sure to use the exact domain name on all of your pages or you will get a «permission denied» error when you call . A common pitfall is accessing your site by , but attempting to call pages with . If you really need to send a request to another domain, see HTTP access control (CORS).
  • The optional third parameter sets whether the request is asynchronous. If (the default), JavaScript execution will continue and the user can interact with the page while the server response has yet to arrive. This is the first A in AJAX.

The parameter to the method can be any data you want to send to the server if -ing the request. Form data should be sent in a format that the server can parse, like a query string:

or other formats, like , JSON, XML, and so on.

Note that if you want to data, you may have to set the MIME type of the request. For example, use the following before calling for form data sent as a query string:

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Путь обучения (образовательная траектория)

В идеале вы должны начать свое учебное путешествие с изучения HTML. Начните с прочтения раздела «Введение в HTML». Затем вы можете перейти к изучению более продвинутых тем, таких как:

  • «CSS (Каскадные таблицы стилей)», и как их использовать для оформления (стилизации) HTML-документа (например, изменение шрифта и его размера, добавление границы и теней для элементов, разбиение страницы на несколько столбцов, добавление анимации и других визуальных эффектов).
  • «JavaScript», и как его использовать для придания динамической функциональности веб-страницам (например, определение вашего местоположения и отображение его на карте, создание элементов, которые будут появлятся/исчезать при нажатии на кнопку, сохранение данных пользователей локально на их компьютерах и многое другое).

Прежде чем приступить к этой теме, вы должны иметь хотя бы базовое представление об использовании компьютеров вообще и уметь «пассивно» использовать Интернет (т.е. уметь просматривать веб-страницы, быть потребителем контента). У вас должна быть базовая рабочая среда, описанная в разделе «Установка базового программного обеспечения», а также вы должны понимать, как создавать файлы и управлять ими, что подробно описано в разделе «Работа с файлами» — обе статьи являются частью нашего модуля для новичков  — «Начало работы с вебом».

Перед тем, как начать эту тему, рекомендуется пройтись по разделу «Начало работы с вебом», однако это необязательно; многое из того, что описано в статье «Основы HTML», также рассматривается и во «Введении в HTML», причём даже более подробно.

Расширение инструментов разработчика

Инструменты разработчика предназначены для расширения. Дополнения Firefox могут получить доступ к инструментам разработчика и компонентам, которые они используют для расширения существующих инструментов и добавления новых инструментов. С помощью протокола удаленной отладки вы можете реализовать свои собственные клиенты и серверы отладки, что позволяет отлаживать веб-сайты с помощью собственных инструментов или отлаживать различные цели с помощью инструментов Firefox.

Use these examples to understand how to implement a devtools add-on.
Write an add-on that adds a new panel to the Toolbox.
Remote Debugging Protocol
The protocol used to connect the Firefox Developer Tools to a debugging target like an instance of Firefox or a Firefox OS device.
A code editor built into Firefox that can be embedded in your add-on.
The Interface
An API that lets JavaScript code observe the execution of other JavaScript code. The Firefox Developer Tools use this API to implement the JavaScript debugger.
How to extend and customize the output of the Web Console and the Browser Console.

Tutorials

Learn how to use HTTP with guides and tutorials.

Overview of HTTP
The basic features of the client-server protocol: what it can do and its intended uses.
HTTP Cache
Caching is very important for fast Web sites. This article describes different methods of caching and how to use HTTP Headers to control them.
HTTP Cookies
How cookies work is defined by RFC 6265. When serving an HTTP request, a server can send a HTTP header with the response. The client then returns the cookie’s value with every request to the same server in the form of a request header. The cookie can also be set to expire on a certain date, or restricted to a specific domain and path.
Cross-Origin Resource Sharing (CORS)
Cross-site HTTP requests are HTTP requests for resources from a different domain than the domain of the resource making the request. For instance, an HTML page from Domain A () makes a request for an image on Domain B () via the element. Web pages today very commonly load cross-site resources, including CSS stylesheets, images, scripts, and other resources. CORS allows web developers to control how their site reacts to cross-site requests.
Evolution of HTTP
A brief description of the changes between the early versions of HTTP, to the modern HTTP/2, the emergent HTTP/3 and beyond.
Mozilla web security guidelines
A collection of tips to help operational teams with creating secure web applications.

Summing Up

To boil everything down to a bullet list, the differences Firefox Developer Edition bring to the table include:

  1. A separate profile so your development environment can be configured differently to your regular browsing environment
  2. Access to cutting edge features not available elsewhere
  3. A 12 week lead time on support for the newest additions to web standards
  4. Default preferences tuned for developers
  5. Dark theme style out of the box

That should clarify the differences between Firefox Developer Edition and regular Firefox, and help you decide if you want to incorporate it into your workflow.

For more on Firefox check out:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector