Delay Loaded Content

Did you ever have the need to load heavy content just after the whole page is loaded?

That is normally achieved with AJAX of some sort; I instead wrapped it in a custom server control, for convenience, which, of course, also uses AJAX anyway.

It uses an ITemplate property that allows us to specify content which will be rendered inside an UpdatePanel but only after a Timer fires. Here is the code:

public class CustomTemplate: ITemplate
{
	public CustomTemplate(Control control)
	{
		this.Control = control;
	}

	public Control Control
	{
		get;
		private set;
	}

	public void InstantiateIn(Control container)
	{
		container.Controls.Add(this.Control);
	}
}


[PersistChildren(false)]
[ParseChildren(true)]
public class DelayLoadedControl : WebControl, INamingContainer
{
	[TemplateContainer(typeof(DelayLoadedControl))]
	[TemplateInstance(TemplateInstance.Single)]
	[PersistenceMode(PersistenceMode.InnerProperty)]
	public ITemplate Template
	{
		get;
		set;
	}

	public Int32 Delay
	{
		get;
		set;
	}

	public UpdatePanelRenderMode RenderMode
	{
		get;
		set;
	}

	public event EventHandler DelayLoad;

	protected void OnTick(Object sender, EventArgs e)
	{
		Timer timer = sender as Timer;
		timer.Enabled = false;

		if (this.Template != null)
		{
			PlaceHolder holder = this.FindControl("holder") as PlaceHolder;
			this.Template.InstantiateIn(holder);
		}

		this.OnDelayLoad(e);
	}

	protected virtual void OnDelayLoad(EventArgs e)
	{
		if (this.DelayLoad != null)
		{
			this.DelayLoad(this, e);
		}
	}

	protected override void CreateChildControls()
	{
		if (this.Visible == true)
		{ 
			Timer timer = new Timer() { ID = "timer", Interval = this.Delay };
			timer.Tick += this.OnTick;

			PlaceHolder holder = new PlaceHolder() { ID = "holder" };

			UpdatePanel panel = new UpdatePanel() { ID = "panel", RenderMode = this.RenderMode, UpdateMode = UpdatePanelUpdateMode.Conditional };

			CustomTemplate template = new CustomTemplate(holder);

			holder.Controls.Add(timer);

			panel.ContentTemplate = template;

			this.Controls.Add(panel);
		}

		base.CreateChildControls();
	}
}

And this is the way to use it:


	


Bookmark and Share

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website