Delay loading of ExtensionHosts until the background page is ready.

BUG=13912
TEST=no

Review URL: http://codereview.chromium.org/159756

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@22302 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/chrome/browser/extensions/extension_host.cc b/chrome/browser/extensions/extension_host.cc
index 78ec493..cbd63a7f 100644
--- a/chrome/browser/extensions/extension_host.cc
+++ b/chrome/browser/extensions/extension_host.cc
@@ -87,6 +87,7 @@
     : extension_(extension),
       profile_(site_instance->browsing_instance()->profile()),
       did_stop_loading_(false),
+      document_element_available_(false),
       url_(url) {
   render_view_host_ = new RenderViewHost(
       site_instance, this, MSG_ROUTING_NONE, NULL);
@@ -132,7 +133,7 @@
 void ExtensionHost::CreateRenderView(RenderWidgetHostView* host_view) {
   render_view_host_->set_view(host_view);
   render_view_host_->CreateRenderView();
-  render_view_host_->NavigateToURL(url_);
+  NavigateToURL(url_);
   DCHECK(IsRenderViewLive());
   NotificationService::current()->Notify(
       NotificationType::EXTENSION_PROCESS_CREATED,
@@ -142,9 +143,24 @@
 
 void ExtensionHost::NavigateToURL(const GURL& url) {
   url_ = url;
+
+  if (!is_background_page() && !extension_->GetBackgroundPageReady()) {
+    // Make sure the background page loads before any others.
+    registrar_.Add(this, NotificationType::EXTENSION_BACKGROUND_PAGE_READY,
+                   Source<Extension>(extension_));
+    return;
+  }
   render_view_host_->NavigateToURL(url_);
 }
 
+void ExtensionHost::Observe(NotificationType type,
+                            const NotificationSource& source,
+                            const NotificationDetails& details) {
+  DCHECK(type == NotificationType::EXTENSION_BACKGROUND_PAGE_READY);
+  DCHECK(extension_->GetBackgroundPageReady());
+  NavigateToURL(url_);
+}
+
 void ExtensionHost::RecoverCrashedExtension() {
   DCHECK(!IsRenderViewLive());
 #if defined(TOOLKIT_VIEWS)
@@ -222,6 +238,12 @@
   did_stop_loading_ = true;
 }
 
+void ExtensionHost::DocumentAvailableInMainFrame(RenderViewHost* rvh) {
+  document_element_available_ = true;
+  if (is_background_page())
+    extension_->SetBackgroundPageReady();
+}
+
 void ExtensionHost::RunJavaScriptMessage(const std::wstring& message,
                                          const std::wstring& default_prompt,
                                          const GURL& frame_url,