Automatically determines whether a CSS or js file is added to the page after the CSS is loaded

  • 2020-03-30 03:56:13
  • OfStack

Recently, in the framework of the project, I wrote a class of querymessagebox to use dialog() in jquery UI to display the message box. In order to make the method easier to call, I added the automatic judgment of whether the page has added ui.js and ui.css. The code is as follows:


//If ui.js is not included, then the reference
if ($('script[src$=""jquery-ui-1.8.11.custom.min.js""]').length == 0) {{ 
$(""<script src='/js/jquery-ui-1.8.11.custom.min.js' type='text/javascript' />"").appendTo('head'); 
}} 
//If the CSS is not loaded, load it
if ($('link[ref$=""jquery-ui-1.8.14.custom.css""]').length == 0) {{ 
$('<link href=""/css/jquery-ui-1.8.14.custom.css"" rel=""stylesheet"" type=""text/css"" />').appendTo('head'); 

//dialog() script 
}}

But CSS code will not immediately load down, so at the time of display dialog does not have the style (can in Internet explorer 9, because under the Internet explorer CSS even after download, also can redraw page elements, while IE8 not). The method to solve this problem, you can use ajax, when CSS loading is completed, display dialog again, this will be displayed with the style, the code is as follows:


if ($('link[ref$=""jquery-ui-1.8.14.custom.css""]').length == 0) { 
$.ajax({ 
url: '/css/jquery-ui-1.8.14.custom.css', 
success: function(data) { 
//Create a style element and append it to the head
//Replace the path of the images in it
$('<style type="text/css">' + data.replace(/url(images/g, 'url(/css/images') + '</style>').appendTo('head'); 
//dialog() script; 
} 
}); 
} 
else { 
//dialog() script; 
}

Related articles: