Asp.net background code dynamically adds references to JS files and css files, jscss
First, add the namespace using System. Web. UI. HtmlControls;
Add reference to css files dynamically in code
HtmlGenericControl myCss = new HtmlGenericControl ();
MyCss. TagName = "link ";
MyCss. Attributes. Add ("type", "text/css ");
MyCss. Attributes. Add ("rel", "stylesheet ");
MyCss. Attributes. Add ("href", ResolveUrl (Page. ResolveClientUrl ("css file path ")));
This. Page. Header. Controls. AddAt (0, myCss );
Dynamically Add references to JS files in code
HtmlGenericControl myJs = new HtmlGenericControl ();
MyJs. TagName = "script ";
MyJs. Attributes. Add ("type", "text/javascript ");
MyJs. Attributes. Add ("src", ResolveUrl (Page. ResolveClientUrl ("js file path ")));
This. Page. Header. Controls. AddAt (1, myJs );
This is a simple method. Record it here.
Some giant websites directly insert js and css code in pages, instead of referencing js or css files.
If these js and CSS are only used on this page, other pages will not be used. The advantage of writing this is to reduce the number of requests sent from the webpage to the server. Speed up web page opening.
Of course, if these js and CSS are used on many pages, it is better to reference files. In this way, the second access can be quickly loaded. Because there is a cache. And easy to modify.
How to dynamically load external CSS and JS files
(Function (){
Xe = window. xe | | {};
Xe. load = {
FilesAdded :{},
LoadScript: function (src ){
If (this. filesAdded [src]) {
Return 0;
}
Var script = document. createElement ('script ');
Script. type = 'text/javascript ';
Script. src = src;
This. filesAdded [src] = true;
Document. body. appendChild (script );
},
LoadScriptString: function (code ){
Var script = document. createElement ('script ');
Script. type = 'text/javascript ';
Try {
Script. appendChild (document. createTextNode (code ));
} Catch (ex ){
Script. text = code;
}
Document. body. appendChild (script );
},
LoadCss: function (href ){
If (this. filesAdded [href]) {
Return 0;
}
Var link = document. createElement ('link ');
Link. type = 'text/css ';
Link. rel = 'stylesheet ';
Link. href = href;
This. filesAdded [href] = true;
Document. getElementsByTagName ('head') [0]. appendChild (link );
},
LoadCssString: function (code ){
Var style = document. createElement ('style ');
Style. type = 'text/css ';
Try {
Style. appendChild (document. createTextNode (code ));
... The remaining full text>