Load css script html

Распространенные способы подключения CSS в JavaScript-приложения

Каждый способ подключения CSS в приложениях React, Vue или Angular имеет свои преимущества и недостатки . Рассмотрим каждый из них более подробно.

Доступные варианты подключения

Рассмотрим некоторые из наиболее часто используемых методов подключения CSS в JavaScript.

Вариант 1: таблица стилей

Мы начнем с привычного подхода – ссылка на один общий файл CSS.

Но по мере того, как приложение становится больше и сложнее, поддерживать единую таблицу стилей будет все труднее. Sass и PostCSS помогут справиться с подобными проблемами.

В зависимости от сложности приложения этот файл CCS будет загружаться асинхронно и блокировать рендеринг остальной части приложения. Поэтому данный метод для небольших приложений.

Тем не менее, общая таблица стилей обеспечивает четкое разделение между бизнес-логикой и стилями приложения. Кроме этого отдельный файл CSS легко кэшируется браузерами.

Вариант 2: Модули CSS

Стили с областями видимости позволяют программно генерировать имена классов, специфичные для конкретного компонента. Область действия CSS определяется конкретным компонентом. Это гарантирует, что имена используемых классов будут уникальными.

Подобная автоматизация приводит к появлению автоматически сгенерированных имен классов, таких как header__2lexd. Часть в конце имени — это хешированный селектор, который является уникальным.

Читайте также:  Gradle run java command

Модули CSS предлагают различные способы управления сгенерированными именами классов. Более подробно об этом можно узнать из документации по модулям .

Представьте, что вы хотите использовать глобальный класс .screen-reader-text, который можно применить к любому компоненту приложения. При использовании CSS-модулей вам придется обратиться к псевдоселектору :global, который определяет размещенные внутри него стили как глобально доступные.

Пока вы импортируете файл CSS, который включает в себя блок объявления :global, в таблицу стилей компонента, вы будете использовать этот глобальный селектор.

Вот пример псевдоселектора :global в действии.

// typography.css :global < .aligncenter < text-align: center; >.alignright < text-align: right; >.alignleft < text-align: left; >>

А с помощью таких инструментов, как PostCSS Nested или Sass, вы можете импортировать шаблоны непосредственно в селектор.

Также обратите внимание на то, как мы ссылаемся на имена классов в узлах DOM. Нужно, чтобы имена отдельных документов для Vue , React и Angular говорили сами за себя. Вот небольшой пример того, как ссылки на классы используются в компоненте React.

// ./css/Button.css .btn < background-color: blanchedalmond; font-size: 1.4rem; padding: 1rem 2rem; text-transform: uppercase; transition: background-color ease 300ms, border-color ease 300ms; &:hover < background-color: #000; color: #fff; >> // ./Button.js import styles from "./css/Button.css"; const Button = () => (  ); export default Button;

Модули CSS позволяют воспользоваться преимуществами стилей с заданной областью видимости без ущерба для производительности приложения.

Также модули CSS можно комбинировать с препроцессорами. Sass, Less, PostCSS могут быть интегрированы в процесс сборки с использованием модулей CSS.

Вариант 3: CSS in JS

Есть несколько пакетов, которые делают создание кода CSS-in-JS максимально безболезненным. JSS , Emotion и Styled Components — это лишь некоторые из них.

CSS-in-JS работает следующим образом. Вы пишете CSS-код, связанный с отдельным компонентом. Во время компиляции приложения используемая платформа выводит CSS-код только тех компонентов, которые постоянно отображаются на веб-странице.

Фреймворки CSS-in-JS выводят связанный CSS-код в теге раздела . Это позволяет оперативно загружать критический CSS. При этом стили имеют ограниченную область действия, а имена классов хэшируются.

При навигации пользователя по приложению стили невостребованных компонентов будут удалены из раздела . На их место будут добавлены стили входящих компонентов. Это повышает производительность приложения, позволяет обойтись без HTTP- запроса и не блокирует рендеринг. Также CSS-in-JS позволяет ссылаться на состояния компонентов и функции для рендеринга стилей CSS.

Основные аспекты использования данного подхода:

  • Некоторые решения CSS-in-JS требуют, чтобы стили были встроены в элемент, который вы пытаетесь стилизовать. Для этого используется очень сложный синтаксис.
  • CSS-in-JS предоставляет мощные инструменты, которые сложно реализовать с помощью модулей CSS или простой таблицы стилей.
  • Нужно уметь использовать новейшие функции CSS, такие как вложенность и переменные.

Пример компонента React с использованием библиотеки Styled Components:

// ./Button.js import styled from 'styled-components'; const StyledButton= styled.button` background-color: blanchedalmond; font-size: 1.4rem; padding: 1rem 2rem; text-transform: uppercase; transition: background-color ease 300ms, border-color ease 300ms; &:hover < background-color: #000; color: #fff; >`; const Button = () => ( Click Me! ); export default Button;

Заключение

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

Источник

The purpose of this tutorial is to teach you how to link to CSS and JavaScript files within an HTML file. It is possible to write CSS and JavaScript directly inside an HTML document, but it is generally best to keep these three languages in their own separate files.

Contents

1. Directory and File Structure

It is a good idea to keep your HTML, CSS, and JavaScript files in separate directories. Create a directory for your project called css-and-js . Inside this directory, create three additional directories. Call them html , css , and javascript .

Inside your html directory, create a file called css-and-js.html . Inside your css directory, create a file called styles.css . And inside your javascript directory, create a file called script.js .

2. HTML

In order to link to your CSS and JavaScript files, you will need an HTML document within which to work. Open css-and-js.html and enter the following HTML:

  lang='en'>  charset='UTF-8'/> Linking to CSS and JavaScript   

Be sure to save your work any time you add code to your files. In the next two sections, we will go over what you need to add to your HTML document in order to link to your CSS and JavaScript.

3. CSS

First, you will need to add something in the body of your HTML to apply styling to. On the next line after the opening tag, indent and add the following:

 If this text is red, then you successfully linked your CSS file! 

As it stands, this text will appear in the color defined as the root color in the browser’s default stylesheet – usually black. In order to change the color of the text, open your styles.css file and add:

The final step in this section is to link to the CSS file inside your HTML document. Enter the following in the section on the line after the closing tag:

 rel='stylesheet' href='../css/styles.css'> 

The element must be placed in the section of the document. Notice that the element is an empty element, so it does not need a closing tag.

The rel attribute defines the relationship between the resource and the HTML document. The href attribute points to your CSS file.

Since the file is located in another directory, you must specify the path by going up one directory using two dots ( .. ), followed by a slash ( / ), the directory your CSS file is in ( css ), another slash, and then your CSS file name ( styles.css ): href=‘../css/styles.css’ .

This is what your HTML document should look like so far:

  lang='en'>  charset='UTF-8'/> Linking to CSS and JavaScript  rel='stylesheet' href='../css/styles.css'>   If this text is red, then you successfully linked your CSS file!   

4. JavaScript

Next, you will need to add some code to your JavaScript file. Open script.js and add:

alert('You successfully linked your JavaScript file!'); 

Save your work and navigate back to your HTML document. The final step is to link to the JavaScript file inside your HTML document. Enter the following in the section on the line after the element:

It is considered the best practice to place the element in the section just before the closing tag.

The src attribute points to your JavaScript file.

Since the JavaScript file is located in another directory, you must specify the path in the src attribute: src=’../javascript/script.js’ .

That’s the last bit of code you will need to enter. This is what your HTML document should look like:

  lang='en'>  charset='UTF-8'/> Linking to CSS and JavaScript  rel='stylesheet' href='../css/styles.css'>   If this text is red, then you successfully linked your CSS file!  src='../javascript/script.js'>   

Be sure to save your work in each of your three files. Now it’s time to see if the links work. Open your css-and-js.html file in the browser of your choice. When you open the file in your browser, you should first encounter an alert box with the message you wrote in your JavaScript file. After clicking OK, the text you entered in the of your HTML should appear red.

If the alert box does not appear or if the text is not red, go back through the steps in this tutorial to ensure everything is entered exactly as shown here.

Congratulations! You’ve now linked to CSS and JavaScript files within an HTML document.

Источник

Using CSS Module Scripts to import stylesheets

Learn how to use CSS module scripts to import CSS stylesheets using the same syntax as JavaScript modules.

Dan Clark

With the new CSS module scripts feature, you can load CSS style sheets with import statements, just like JavaScript modules. The style sheets can then be applied to documents or shadow roots in the same manner as constructable stylesheets. This can be more convenient and more performant than other ways of importing and applying CSS.

Browser Support #

CSS module scripts are available by default in Chrome and Edge in version 93.

Support in Firefox and Safari is not yet available. Implementation progress can be tracked at the Gecko bug and WebKit bug, respectively.

Prerequisites #

Using CSS module scripts #

Import a CSS module script and apply it to a document or a shadow root like this:

import sheet from './styles.css' assert  type: 'css' >;
document.adoptedStyleSheets = [sheet];
shadowRoot.adoptedStyleSheets = [sheet];

The default export of a CSS module script is a constructable stylesheet whose contents are those of the imported file. Like any other constructable stylesheet, it is applied to documents or shadow roots using adoptedStyleSheets .

Unlike other ways of applying CSS from JavaScript, there is no need to create &LTstyle> elements or mess with JavaScript strings of CSS text.

CSS modules also have some of the same benefits as JavaScript modules.

  • Deduplication: if the same CSS file is imported from multiple places in an application, it will still only be fetched, instantiated, and parsed a single time.
  • Consistent order of evaluation: when the importing JavaScript is running, it can rely on the stylesheet it imports having already been fetched and parsed.
  • Security: modules are fetched with CORS and use strict MIME-type checking.

Import Assertions (what’s with the ‘ assert ‘?) #

The assert < type: 'css' >part of the import statement is an import assertion. This is required; without it, the import is treated as a normal JavaScript module import, and will fail if the imported file has a non-JavaScript MIME type.

import sheet from './styles.css'; // Failed to load module script: 
// Expected a JavaScript module
// script but the server responded
// with a MIME type of "text/css".

Dynamically imported stylesheets #

You can also import a CSS module using dynamic import, with a new second parameter for the type: ‘css’ import assertion:

const cssModule = await import('./style.css',  
assert: type: 'css' >
>);
document.adoptedStyleSheets = [cssModule.default];

Note that it’s cssModule.default (not cssModule itself) that is added to adoptedStyleSheets . This is because the object returned from dynamic import() is a module namespace object. The CSSStyleSheet is the default export of the module, so it’s accessed at cssModule.default .

@import rules not yet allowed #

Currently CSS @import rules don’t work in constructable stylesheets, including CSS module scripts. If @import rules are present in a constructable stylesheet, those rules will be ignored.

/* atImported.css */
div
background-color: blue;
>
/* styles.css */
@import url('./atImported.css'); /* Ignored in CSS module */
div
border: 1em solid green;
>
<!-- index.html -->
script type="module">
import styles from './styles.css' assert type: "css" >;
document.adoptedStyleSheets = [styles];
</script>
div>This div will have a green border but no background color.</div>

Support for @import in CSS module scripts may be added to the specification. Track this specification discussion in the GitHub issue.

Источник

Оцените статью