Portal Engine Questions on portal engine and web parts.
Version 7.x > Portal Engine > Including scripts with web part View modes: 
User avatar
Member
Member
jwynveen - 11/4/2013 4:22:45 PM
   
Including scripts with web part
What is the recommended way to include javascript files with web parts? For example, if I were to build a web part for a fancy box image gallery, I would need to include the plugin script (either via CDN or hosted locally within the site) as well as the initialization script on page load.

These are the three options I know of right now, but I don't like any of them and am hoping there is a better way:

1) I could put the <script> tags in the .ascx file, but that would load the scripts in the middle of the page which isn't recommended.
2) I could do something like a RegisterClientScript in the .ascx.cs, but pulling in client-side code through server-side code always feels wrong to me.
3) I could add a javascript web part to a template when I add this new web part. This is able to locate the scripts at the end of the page like I want, but it creates a dependency between web parts that isn't ideal.

What I'm really hoping for is something similar to how CSS styles can be included with a web part. Or if there was some system property of the web part that I could set that would always include my script files. How is this normally done?

User avatar
Kentico Legend
Kentico Legend
Brenden Kehren - 11/5/2013 7:12:29 AM
   
RE:Including scripts with web part
If your webpart is dependent on the .js files, I'd suggest following the best practices Kentico offers in the DevGuide. For instance if your webparts files are named MyWebPart.ascx you'd create a folder named MyWebPart_files and place your files in there (.js, .css, images, etc). Then in your webpart code you reference that location.

If you are simply using a repeater or other listing viewer to display content on a page and want to use a fancy box or something like that, you can add the JavaScript webpart to the page and place your script or location of the script in there. Then name it accordingly so it's easy to identify.

User avatar
Member
Member
jwynveen - 11/5/2013 9:32:04 AM
   
RE:Including scripts with web part
So then is the best practice to include them in the .ascx file via <script> tags, or to include them in the code behind with something like RegisterClientScript()?

User avatar
Kentico Legend
Kentico Legend
Brenden Kehren - 11/5/2013 3:36:08 PM
   
RE:Including scripts with web part
You have more control with the code behind than you do with the .ascx file. That is your preference I'd guess.

User avatar
Member
Member
kentico_sandroj - 11/11/2013 2:01:47 PM
   
RE:Including scripts with web part
Hello,

As FroggEye mentioned, it really depends on your preference. If you are looking for the "cleanest" approach, this one may work well.

Best Regards,
Sandro