Tuesday, May 13, 2014

How to register Javascript & CSS file in custom webpart

In this post will explain about how we can register CSS and Javascript files in the webpart code.

What are the advantages of registering CSS and JS file through webpart?

Lets assume if we register CSS and JS file in masterpage every time this files will be loaded irrespective of whether webpart rendered in the page or not. This will be increase response time for the page. To overcome this we can register CSS and JS file in the webpart.

How we can achieve this?

If we are using custom webpart then in the on pre render method we can use below snippet of code to register the CSS & JS file.


protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            try
            {
                //This is the sharepoint layout mapped folder which contain jQuery and javascript file
                ScriptLink.Register(this.Page, "/_layouts/Scripts/jquery-1.9.1.min.js", false);
                ScriptLink.Register(this.Page, "/_layouts/Scripts/customJS.js", false);

                CssRegistration wpCss = new CssRegistration();
                //Location of the CSS file path
                wpCss.Name = "FilePath";
                //Lets assume we need to load the webpart CSS file after the main CSS file or it may                   be after core.css file
                wpCss.After = "MainFileName";
                this.Controls.Add(wpCss);
            }
            catch (Exception ex)
            {
            }
        }

No comments:

Post a Comment