Javascript add css stylesheet to head

Динамическое добавление таблицы стилей CSS на HTML-страницу с помощью JavaScript/jQuery.

В этом посте мы обсудим, как динамически добавить таблицу стилей CSS на HTML-страницу с помощью JavaScript и jQuery.

1. Использование jQuery

Если вы работаете с jQuery, вы можете использовать .appendTo() метод для добавления таблицы стилей в конце элемент текущего документа. Вот как это сделать:

Здесь альтернативная версия с использованием .append() метод:

С $.ajax() метод, вы можете загрузить CSS с сервера и заключить содержимое в теги и, наконец, добавьте его в конец элемент текущего документа. Следующий код демонстрирует это, динамически загружая библиотеку начальной загрузки.

Здесь альтернативная версия с использованием .load() метод:

2. Использование JavaScript

В ванильном JavaScript вы можете использовать собственный createElement() способ создания таблицы стилей и appendChild() способ добавления таблицы стилей в конец элемент текущего документа. Вот как мы можем это сделать:

Кроме того, вы можете поиграть с innerHTML свойство Document.head .

Это все о динамическом добавлении таблицы стилей CSS на HTML-страницу с использованием JavaScript и jQuery.

Средний рейтинг 4.58 /5. Подсчет голосов: 31

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

Add Stylesheet to Head Using JavaScript in Body

Update: According to specs, the link element is not allowed in the body. However, most browsers will still render it just fine. So, to answer the questions in the comments — one really has to add link to the head of the page and not the body .

function addCss(fileName)  
var head = document.head;
var link = document.createElement("link");

link.type = "text/css";
link.rel = "stylesheet";
link.href = fileName;

head.appendChild(link);
>

addCss('');

Or a little bit easier with jquery

function addCss(fileName) var link = $("", rel: "stylesheet", 
type: "text/css",
href: fileName
>)
$('head').append(link);
>

addCss("");

You don’t need necessarily add it to the head, just add it to the end of body tag.

as Juan Mendes mentioned, you can insert stylesheet to the head instead

And the same without jQuery (see code above)

Add CSS to with JavaScript?

As you are trying to add a string of CSS to with JavaScript?
injecting a string of CSS into a page it is easier to do this with the element than the element.

Читайте также:  Class php получить переменную

The following adds p < color: green; >rule to the page.

You can create this in JavaScript simply by URL encoding your string of CSS and adding it the HREF attribute. Much simpler than all the quirks of elements or directly accessing stylesheets.

var linkElement = this.document.createElement('link');
linkElement.setAttribute('rel', 'stylesheet');
linkElement.setAttribute('type', 'text/css');
linkElement.setAttribute('href', 'data:text/css;charset=UTF-8,' + encodeURIComponent(myStringOfstyles));

This will work in IE 5.5 upwards

The solution you have marked will work but this solution requires fewer dom operations and only a single element.

How to create a tag with Javascript?

Try adding the style element to the head rather than the body .

This was tested in IE (7-9), Firefox, Opera and Chrome:

var css = 'h1 < background: red; >', 
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');

head.appendChild(style);

style.type = 'text/css';
if (style.styleSheet) // This is required for IE8 and below.
style.styleSheet.cssText = css;
> else style.appendChild(document.createTextNode(css));
>

Adding CSS to head tag from the body using jQuery

It’s a question of readability vs performance, I think.

People would argue (and they’d be normally correct) that doing stuff the raw Javascript way is faster than if done with jQuery — and why wouldn’t that be? jQuery abstracts the raw Javascript calls from what you’re doing to present nice syntax and convenience. That means that you’ll incur additional overhead when using jQuery, as your commands will zig and zag through it’s innards until it gets to the part where it «translates» what you’re doing into raw Javascript code.

But then again, writing raw Javascript code can not only be tedious from time to time (just look at all that code!), but also susceptible to cross-browser problems (which jQuery attempts to normalize), and can be harder to read to the uninitiated. Is the performance benefit really worth it?

It’s a matter of where and what you’re trying to do, honestly. Here, I’d say that the benefits of going raw Javascript is negligible. Hit that up in jQuery.

Inject CSS stylesheet as string using Javascript

There are a couple of ways this could be done, but the simplest approach is to create a element, set its textContent property, and append to the page’s .

/** 
* Utility function to add CSS in multiple passes.
* @param styleString
*/
function addStyle(styleString) const style = document.createElement('style');
style.textContent = styleString;
document.head.append(style);
>

addStyle(`
body color: red;
>
`);

addStyle(`
body background: silver;
>
`);

If you want, you could change this slightly so the CSS is replaced when addStyle() is called instead of appending it.

/** 
* Utility function to add replaceable CSS.
* @param styleString
*/
const addStyle = (() => const style = document.createElement('style');
document.head.append(style);
return (styleString) => style.textContent = styleString;
>)();

addStyle(`
body color: red;
>
`);

addStyle(`
body background: silver;
>
`);

IE edit: Be aware that IE9 and below only allows up to 32 stylesheets, so watch out when using the first snippet. The number was increased to 4095 in IE10.

2020 edit: This question is very old but I still get occasional notifications about it so I’ve updated the code to be slightly more modern and replaced .innerHTML with .textContent . This particular instance is safe, but avoiding innerHTML where possible is a good practice since it can be an XSS attack vector.

Читайте также:  Java net socket expection

How to load up CSS files using Javascript?

Here’s the «old school» way of doing it, which hopefully works across all browsers. In theory, you would use setAttribute unfortunately IE6 doesn’t support it consistently.

var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://website.example/css/stylesheet.css';
link.media = 'all';
head.appendChild(link);
>

This example checks if the CSS was already added so it adds it only once.

Put that code into a JavaScript file, have the end-user simply include the JavaScript, and make sure the CSS path is absolute so it is loaded from your servers.

VanillaJS

Here is an example that uses plain JavaScript to inject a CSS link into the head element based on the filename portion of the URL:


var file = location.pathname.split( "/" ).pop();

var link = document.createElement( "link" );
link.href = file.substr( 0, file.lastIndexOf( "." ) ) + ".css";
link.type = "text/css";
link.rel = "stylesheet";
link.media = "screen,print";

document.getElementsByTagName( "head" )[0].appendChild( link );

Insert the code just before the closing head tag and the CSS will be loaded before the page is rendered. Using an external JavaScript ( .js ) file will cause a Flash of unstyled content (FOUC) to appear.

Add css to head and refresh it dynamically with javascript

This is all you need, it will change the background-position in runtime.

$(window).on('scroll touchmove', function(e) var newposition = ($(document).scrollTop() * 0.4).toFixed(2); 
$('body').css('background-position', '0px ' + newposition + 'px');
>);

Here is an example at jsFiddle.

How do you add CSS with Javascript?

You can also do this using DOM Level 2 CSS interfaces (MDN):

var sheet = window.document.styleSheets[0];
sheet.insertRule('strong < color: red; >', sheet.cssRules.length);

. on all but (naturally) IE8 and prior, which uses its own marginally-different wording:

sheet.addRule('strong', 'color: red;', -1);

There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don’t have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘

You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn’t matter. If there isn’t one, the only standard way to create it at the moment is with createElement.

Источник

Setting CSS Styles with JavaScript

Setting CSS Styles with JavaScript

Why is there a need to change CSS with Javascript? Let’s discuss a few cases where changing CSS styles in Javascript makes sense.

  1. To load stylesheets dynamically.
  2. After an initial page render, sometimes, there will be a need to change a particular style for the element in a page dynamically. In cases like this, writing CSS in Javascript helps.
  3. If on any webpage some progress is happening and we want to change the look and feel after progress is finished. Here as well, changing styles in Javascript helps.
  4. Many developers are much more confident in writing Javascript than CSS, for those, it is hard to write and maintain CSS. So they like to write CSS in Javascript. There are libraries that allow to style components with CSS in Javascript like style components.
Читайте также:  From keyword import python

Above are a few which I can think of, but I am sure there are many.

How to change CSS with Javascript?

There are different ways of setting CSS with Javascript for different scenarios. Below is the list :

  • Inline style
  • Adding or removing class names from the element
  • Global styles
  • Adding or replacing stylesheets
  • Inserting CSS rules

Let’s discuss each one in detail.

Inline style is the way to add styles directly to elements. The highlighted part of the devtool image below shows how red color and font size got added to the title. Inline styles can also be written directly on an element, but here we will look at how we can achieve the inline style in Javascript.

Adding red color and font size to the title

Adding red color and font size to the title

We have an H1 element with the default styles and with an Id attribute, which has a value ‘title’. Below is the image which shows HTML view, browser view and devtool view of the H1 element.

HTML view, browser view, and devtool view of the H1 element.

HTML view, browser view, and devtool view of the H1 element.

Now, will change the font size and color of the H1 element to 50px and red respectively. In CSS we will apply styles on elements ID.

Источник

How to Add CSS Styles with JavaScript?

selective focus photography of seal lying on ground

Sometimes, we want to add CSS styles dynamically into our web page with JavaScript.

In this article, we’ll look at ways to add CSS styles dynamically with JavaScript.

Using the window.document.styleSheets Object and the insertRule Method

We can get the first stylesheet for a document with the window.document.styleSheets property.

Then we can call the insertRule method on the returned stylesheet object.

For instance, if we have the following HTML code:

hello world 

Then we can make the strong element text display in red by writing:

const [sheet] = window.document.styleSheets; sheet.insertRule('strong < color: red; >', sheet.cssRules.length); 

We use the destructuring syntax to get the first stylesheet from the window.document.styleSheets iterable object.

Then we call insertRule on the stylesheet object with our CSS string as the first argument.

Then we should see that the strong element text is red.

Create a style Element

Another way to add CSS styles with JavaScript is to use the document.createElement method to create a style element.

For instance, if we have the following HTML code:

hello world 

Then we can create the style element by writing:

const styleSheet = document.createElement("style") styleSheet.type = "text/css" styleSheet.innerText = 'strong < color: red; >' document.head.appendChild(styleSheet) 

We call document.createElement with ‘style’ to create a style element.

Then we set the type property on the resulting styleSheet object.

And then we set the innerText property to the CSS styles we want to apply.

Finally, we call document.head.appendChild with styleSheet to append the style element we created into the head element as its child.

Therefore, we should get the same result as before.

Conclusion

We can add CSS styles with JavaScript by creating a style element or getting the first style sheet with JavaScript and add the style rules we want to it.

Источник

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