- Динамическое добавление таблицы стилей CSS на HTML-страницу с помощью JavaScript/jQuery.
- 1. Использование jQuery
- 2. Использование JavaScript
- Dynamically Add JavaScript and CSS Files to Your Website Using JavaScript
- The Ideal Scenario
- Doing It On The Client Side (JavaScript)
- Using jQuery
- Load Order
- How to load CSS files using JavaScript?
- Example 1: Loading the CSS file on window.onload( )
- Code For loadcss1.html
- Example 1
- Code For cssfilenew.css
- Viewing The Result
- Example2: Loading the different CSS files on click of two buttons
- Code For loadcss2.html:
- Example 1
- Code For cssfile.css
- Code For cssfilenew.css
- Viewing The Result
Динамическое добавление таблицы стилей 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, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно
Dynamically Add JavaScript and CSS Files to Your Website Using JavaScript
When you can’t use a JavaScript or CSS concatenater, this method can be useful for adding scripts and styles to your site on the fly.
This is how we typically add JavaScript and CSS files to websites:
script type="text/javascript" src="path/to/script.js"> script>
link href="path/to/stylesheet.css" rel="stylesheet" type="text/css" />
The Ideal Scenario
But, as your site gets super awesome, it can also get super cluttered. For example, with stylesheets, you’re either going to have a giant, messy stylesheet, or (preferably) you’re going to have a handful of (let’s hope) nicely-organized stylesheets. The downside to that is the section of your HTML markup is going to get messy. That’s not to mention that every request for a file, like a stylesheet, takes time and resources, and will slow your site down.
Ideally, you should compile these files into a single, manifest file. There are plenty of tools out there to help you with this. Compass and Gulp are a couple examples.
And if you’re using a server-side language to build your site (something like Ruby or PHP), you have even more tools available to you.
Doing It On The Client Side (JavaScript)
If you can’t make the ideal scenario happen, an okay option is to add these scripts and styles via a single script.
To do so, add something like this to the of your document (hopefully you have a single master page or header file, so you only have to do this once):
script type="text/javascript" src="path/to/controller.js"> script>
You’ll want to add this to the end of your section, so it is the last script loaded.
Note: There is a small chance of introducing an errors using this method. Because your scripts are being loaded in your head instead of at the end of your body, your page may not load if there is a JavaScript error. Also, be aware that other JavaScript files may be loaded after this if they are either loaded dynamically or are loaded at the end of the body.
Now, in your controller.js file, add this function:
function loadFile(path, type)
if (type == "js")
var fileref = document.createElement("script");
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", path);
> else if (type == "css")
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", path);
>
document.getElementsByTagName("head")[0].appendChild(fileref);
>
Below that function (in controller.js) you can call all your JS and CSS files, like so:
// Stylesheets
loadFile("path/to/file.css", "css");
// Scripts
loadFile("path/to/file.js", "js");
Now your files should load no problem!
Using jQuery
A somewhat cleaner method is to write the same function using jQuery. To do so, your document would need this markup:
script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> script>
script type="text/javascript" src="path/to/controller.js"> script>
Notice here we’re loading the jQuery library first, so we can use it in controller.js . I’m loading this library from Google Libraries, but you can certainly add it however you’d like.
Now, in the controller.js file:
function loadFile(path, type)
if (type == "js")
$("head").append(
' '
);
> else if (type == "css")
$("head").append(
' + path + '" rel="stylesheet" type="text/css">'
);
>
>
And you would add your files in the same manner as before.
// Stylesheets
loadFile("path/to/file.css", "css");
// Scripts
loadFile("path/to/file.js", "js");
As you can see, this is much cleaner, but unless you’re planning to use the jQuery library throughout your JS code, it’s not worth loading the entire library for this one function.
Load Order
You can’t always be sure how your browser is going to handle the load order of your scripts. If you’re scripts have interwoven dependencies, then you may consider using a tool like RequireJS to ensure your scripts are loaded in the appropriate order.
How to load CSS files using JavaScript?
Sometimes, the task is change the page themes and to use different CSS files on the same page content. In such tasks the need is to fetch a CSS and load it dynamically while selecting a theme. In this case the CSS file has to be accessed, loaded and even selected through a javascript program. Using HTML and javascript code this process of loading the CSS file is demonstrated in this article. This is shown by using two different examples. In the first example, a CSS file is selected on the windows load event. In the second example, two buttons are used to load separate CSS files on button clicks.
Example 1: Loading the CSS file on window.onload( )
Folder and Pages Design Steps −
- Step 1 − Make an html file and start writing the code. Create a CSS file and define the styles for background, p tag and h1 tag.
- Step 2 − Inside the tags in the html file, write the code which will be executed when the page is fully loaded. Use window.onload() for this.
- Step 3 − Inside the tags write the code to fetch the head tag first. Then make a link tag and set its properties.
- Step 4 − Select the css file and add it to the href of the link.
- Step 5 − Now add this created link into the head tag.
- Step 6 − Load the HTML file in a browser and check the result.
Main html file : loadcss1.html
CSS file used: cssfilenew.css
Code For loadcss1.html
Example 1
To load the CSS file using JS
Code For cssfilenew.css
Viewing The Result
For seeing the result open the html file in a browser. The styles will be included in the CSS file that is loaded using Javascript.
Example2: Loading the different CSS files on click of two buttons
Folder and Pages Design Steps −
Step 1 − Make an HTML file and start writing the code. Create two CSS files and define the different styles for the background, p tag, and h1 tag in these.
Step 2 − Inside the tags in the HTML file, make two functions, function1, and function2. Write the code for these functions which will be executed when these functions will be called.
Step 3 − Inside the tags, in both of these functions write the code to fetch the head tag first. Then make a link tag and set its properties.
Step 4 − Select the different CSS files through both functions and add these to the href of the link.
Step 5 − Add this created link to the head tag.
Step 6 − Now create two buttons and call these two functions on different button clicks.
Step 7 − Load the HTML file in a browser. The CSS file is not added initially. It will be added on the button clicks. Click both buttons and check the results.
Main HTML file: loadcss2.html
CSS files used: cssfile.css and cssfilenew.css
Code For loadcss2.html:
Example 1
To load the CSS file using JS
Code For cssfile.css
Code For cssfilenew.css
Viewing The Result
For seeing the result open the html file in a browser. The styles will be included from the CSS files that are loaded on button clicks.
3In this article, using two different examples, the ways to show how to load the CSS file dynamically using the javascript code are given. First, the method is given where a CSS file is selected when the page is loaded and then the way of using the CSS files on button click is given. For this two buttons are clicked to load different CSS files and change the style of the same page.