How to add CSS and JS resource files into nopCommerce Plugin Views
If you are a nopCommerce developer you will definitely come across a situation where you need to add a custom resource files like CSS and JS to your nopCommerce plugin’s view files.
For most developers working on the nopCommerce for the first time, the simplest way to add such files is to directly add their references into plugin’s view files. However, this is highly not recommended. For your nopCommerce plugin to work correctly, you need to ensure that you’re using the standard way to add your resources.
If you already know, nopCommerce do a bundling of the JS and CSS files on the fly for performance optimization. However, if you’re using a direct link to resource files, it won’t include your JS and CSS files during bundling. Moreover, there may be chances of other issues as well.
So here are the simple steps for you to add your custom resource files into your nopCommerce plugin’s view files.
Before you begin, you should have a well organized plugin folder structure. For CSS you can use Content folder, and for storing your JS files, you may use Script folder. Here is the screen shot from one of the existing plugin of nopCommerce.
Move your CSS and JS files into appropriate folder. It is not compulsory to follow this folder structure, but if you’re using standard structure then it becomes easier for your and others working on it in future, and you don’t need to remember where you stored it.
Now, to load resource files correctly you need to add its references into your plugin’s view files.
You can use Html.AddScriptParts() or Html.AddCssFileParts() helper methods.
- Html.AddCssFileParts() method has two parameters first is optional and second is required.
- Html.AddScriptParts() method has three parameters first and third is optional and second is required.
You can check into more details about this methods by going to its definition in your nopCommerce projects.
Coming to the point, here is how you can add resources into your Plugin’s view file.
@{ //Loading CSS file Html.AddCssFileParts(ResourceLocation.Head, "~/Plugins/{PluginName}/Content/{CSSFileName.Css}"); //Loading js file //Third parameter value indicating whether to exclude this script from bundling Html.AddScriptParts(ResourceLocation.Foot, "~/Plugins/{PluginName}/Scripts/{JSFileName.js}", true); }
If you want to add resource link in the header then you can use ResourceLocation.Head and for footer you can use ResourceLocation.Foot. Note that you need to give correct plugin name and resource file name in above, and then it will work.
If you have any question, make sure to post your issue at nopCommerce forum. And if you’re looking for professional nopCommerce development company, make sure to checkout the amazing nopCommerce services we offer.