Hello!
There is an HTML file, in the head of which, with the help of a script, a CSS file is dynamically connected (in order to entertain Google page speed). After this script, the remaining JS-libraries and scripts are connected. If the script is trying to get the style of the element, the browser style is displayed.
Example: There is a div with the class .test. In the CSS file connected via the script, the width of the .test block is specified (width = 200px). But if you request the width from the script, then the default width of 1920px (the width of the browser window) will be received, as if the file did not connect with the style.
Adding style and connecting scripts (at the end of the body)
<!-- Load CSS --> <script> function LoadFile(arrLibs){ var i, ext, file, link; for( i = 0; i < arrLibs.length; i++ ){ file = arrLibs[i]; link = document.createElement("link"); link.setAttribute("rel", "stylesheet"); link.setAttribute("type", "text/css"); link.setAttribute("href", file); document.getElementsByTagName("head")[0].appendChild(link) console.log('1.'+i); } } var arrLibs = [ 'css/style.css' ]; LoadFile(arrLibs); console.log('1'); </script> <!-- Load CSS --> <!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/jquery-2.2.4.min.js"><\/script>')</script> <!-- jQuery --> <!-- JS Libs --> <script src="js/libs.min.js"></script> <!-- JS Libs --> <!-- Custom js --> <script src="js/main.js"></script> <!-- Custom js --> If you postpone the execution of the script, then everything works fine
$(function(){ var interval = setTimeout(function(){ console.log( $('.test').width() ); },200); }); Question: How to add CSS to a page using a script so as to access it from JS without crutches?
$(window).load(function() { console.log( $('.test').width() ); })- Sasha Omelchenko