Bug 1480720 - Factor out script fetch options from script load request classes r=baku
authorJon Coppeard <jcoppeard@mozilla.com>
Mon, 06 Aug 2018 10:54:28 +0100
changeset 430225 5f9c8d7612a7e44685a7c64815d86f5299f1b8b3
parent 430224 7e1f880b5f882732370ad70d02e7378b14b302f8
child 430226 d08917025fe0c6cf2146821dc75f5401fbdb62ec
push id106091
push userjcoppeard@mozilla.com
push dateMon, 06 Aug 2018 09:54:46 +0000
treeherdermozilla-inbound@5f9c8d7612a7 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersbaku
bugs1480720
milestone63.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1480720 - Factor out script fetch options from script load request classes r=baku
dom/script/ModuleLoadRequest.cpp
dom/script/ModuleLoadRequest.h
dom/script/ScriptLoadHandler.cpp
dom/script/ScriptLoadRequest.cpp
dom/script/ScriptLoadRequest.h
dom/script/ScriptLoader.cpp
dom/script/ScriptLoader.h
--- a/dom/script/ModuleLoadRequest.cpp
+++ b/dom/script/ModuleLoadRequest.cpp
@@ -23,52 +23,45 @@ NS_IMPL_CYCLE_COLLECTION_INHERITED(Modul
                                    mLoader,
                                    mModuleScript,
                                    mImports)
 
 NS_IMPL_ADDREF_INHERITED(ModuleLoadRequest, ScriptLoadRequest)
 NS_IMPL_RELEASE_INHERITED(ModuleLoadRequest, ScriptLoadRequest)
 
 ModuleLoadRequest::ModuleLoadRequest(nsIURI* aURI,
-                                     nsIScriptElement* aElement,
-                                     CORSMode aCORSMode,
+                                     ScriptFetchOptions* aFetchOptions,
                                      const SRIMetadata& aIntegrity,
                                      nsIURI* aReferrer,
-                                     mozilla::net::ReferrerPolicy aReferrerPolicy,
                                      ScriptLoader* aLoader)
   : ScriptLoadRequest(ScriptKind::eModule,
                       aURI,
-                      aElement,
-                      aCORSMode,
+                      aFetchOptions,
                       aIntegrity,
-                      aReferrer,
-                      aReferrerPolicy),
+                      aReferrer),
     mIsTopLevel(true),
     mLoader(aLoader),
     mVisitedSet(new VisitedURLSet())
 {
   mVisitedSet->PutEntry(aURI);
 }
 
 ModuleLoadRequest::ModuleLoadRequest(nsIURI* aURI,
                                      ModuleLoadRequest* aParent)
   : ScriptLoadRequest(ScriptKind::eModule,
                       aURI,
-                      aParent->mElement,
-                      aParent->mCORSMode,
+                      aParent->mFetchOptions,
                       SRIMetadata(),
-                      aParent->mURI,
-                      aParent->mReferrerPolicy),
+                      aParent->mURI),
     mIsTopLevel(false),
     mLoader(aParent->mLoader),
     mVisitedSet(aParent->mVisitedSet)
 {
   MOZ_ASSERT(mVisitedSet->Contains(aURI));
 
-  mTriggeringPrincipal = aParent->mTriggeringPrincipal;
   mIsInline = false;
   mScriptMode = aParent->mScriptMode;
 }
 
 void
 ModuleLoadRequest::Cancel()
 {
   ScriptLoadRequest::Cancel();
--- a/dom/script/ModuleLoadRequest.h
+++ b/dom/script/ModuleLoadRequest.h
@@ -39,21 +39,19 @@ class ModuleLoadRequest final : public S
   ModuleLoadRequest(ModuleLoadRequest&& aOther) = delete;
 
 public:
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(ModuleLoadRequest, ScriptLoadRequest)
 
   // Create a top-level module load request.
   ModuleLoadRequest(nsIURI* aURI,
-                    nsIScriptElement* aElement,
-                    CORSMode aCORSMode,
+                    ScriptFetchOptions* aFetchOptions,
                     const SRIMetadata& aIntegrity,
                     nsIURI* aReferrer,
-                    mozilla::net::ReferrerPolicy,
                     ScriptLoader* aLoader);
 
   // Create a module load request for an imported module.
   ModuleLoadRequest(nsIURI* aURI,
                     ModuleLoadRequest* aParent);
 
   bool IsTopLevel() const override
   {
--- a/dom/script/ScriptLoadHandler.cpp
+++ b/dom/script/ScriptLoadHandler.cpp
@@ -218,17 +218,17 @@ ScriptLoadHandler::EnsureDecoder(nsIIncr
       return true;
     }
   }
 
   // Check the hint charset from the script element or preload
   // request.
   nsAutoString hintCharset;
   if (!mRequest->IsPreload()) {
-    mRequest->mElement->GetScriptCharset(hintCharset);
+    mRequest->Element()->GetScriptCharset(hintCharset);
   } else {
     nsTArray<ScriptLoader::PreloadInfo>::index_type i =
       mScriptLoader->mPreloads.IndexOf(mRequest, 0,
             ScriptLoader::PreloadRequestComparator());
 
     NS_ASSERTION(i != mScriptLoader->mPreloads.NoIndex,
                  "Incorrect preload bookkeeping");
     hintCharset = mScriptLoader->mPreloads[i].mCharset;
@@ -296,46 +296,46 @@ ScriptLoadHandler::EnsureKnownDataType(n
   if (ScriptLoader::BinASTEncodingEnabled()) {
     nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(req);
     if (httpChannel) {
       nsAutoCString mimeType;
       httpChannel->GetContentType(mimeType);
       if (mimeType.LowerCaseEqualsASCII(APPLICATION_JAVASCRIPT_BINAST)) {
         if (mRequest->ShouldAcceptBinASTEncoding()) {
           mRequest->SetBinASTSource();
-          TRACE_FOR_TEST(mRequest->mElement, "scriptloader_load_source");
+          TRACE_FOR_TEST(mRequest->Element(), "scriptloader_load_source");
           return NS_OK;
         } else {
           return NS_ERROR_FAILURE;
         }
       }
     }
   }
 
   if (mRequest->IsLoadingSource()) {
     mRequest->SetTextSource();
-    TRACE_FOR_TEST(mRequest->mElement, "scriptloader_load_source");
+    TRACE_FOR_TEST(mRequest->Element(), "scriptloader_load_source");
     return NS_OK;
   }
 
   nsCOMPtr<nsICacheInfoChannel> cic(do_QueryInterface(req));
   if (cic) {
     nsAutoCString altDataType;
     cic->GetAlternativeDataType(altDataType);
     if (altDataType.Equals(nsContentUtils::JSBytecodeMimeType())) {
       mRequest->SetBytecode();
-      TRACE_FOR_TEST(mRequest->mElement, "scriptloader_load_bytecode");
+      TRACE_FOR_TEST(mRequest->Element(), "scriptloader_load_bytecode");
     } else {
       MOZ_ASSERT(altDataType.IsEmpty());
       mRequest->SetTextSource();
-      TRACE_FOR_TEST(mRequest->mElement, "scriptloader_load_source");
+      TRACE_FOR_TEST(mRequest->Element(), "scriptloader_load_source");
     }
   } else {
     mRequest->SetTextSource();
-    TRACE_FOR_TEST(mRequest->mElement, "scriptloader_load_source");
+    TRACE_FOR_TEST(mRequest->Element(), "scriptloader_load_source");
   }
 
   MOZ_ASSERT(!mRequest->IsUnknownDataType());
   MOZ_ASSERT(mRequest->IsLoading());
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/dom/script/ScriptLoadRequest.cpp
+++ b/dom/script/ScriptLoadRequest.cpp
@@ -12,75 +12,98 @@
 #include "nsICacheInfoChannel.h"
 #include "ScriptLoadRequest.h"
 #include "ScriptSettings.h"
 
 namespace mozilla {
 namespace dom {
 
 //////////////////////////////////////////////////////////////
+// ScriptFetchOptions
+//////////////////////////////////////////////////////////////
+
+NS_IMPL_CYCLE_COLLECTION(ScriptFetchOptions,
+                         mElement,
+                         mTriggeringPrincipal)
+
+NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(ScriptFetchOptions, AddRef)
+NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(ScriptFetchOptions, Release)
+
+ScriptFetchOptions::ScriptFetchOptions(mozilla::CORSMode aCORSMode,
+                                       mozilla::net::ReferrerPolicy aReferrerPolicy,
+                                       nsIScriptElement* aElement,
+                                       nsIPrincipal* aTriggeringPrincipal)
+  : mCORSMode(aCORSMode)
+  , mReferrerPolicy(aReferrerPolicy)
+  , mElement(aElement)
+  , mTriggeringPrincipal(aTriggeringPrincipal)
+{
+  MOZ_ASSERT(mTriggeringPrincipal);
+}
+
+ScriptFetchOptions::~ScriptFetchOptions()
+{}
+
+//////////////////////////////////////////////////////////////
 // ScriptLoadRequest
 //////////////////////////////////////////////////////////////
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(ScriptLoadRequest)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(ScriptLoadRequest)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(ScriptLoadRequest)
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(ScriptLoadRequest)
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(ScriptLoadRequest)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mElement)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK(mFetchOptions)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mCacheInfo)
   tmp->DropBytecodeCacheReferences();
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(ScriptLoadRequest)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mElement)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFetchOptions)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCacheInfo)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(ScriptLoadRequest)
   NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mScript)
 NS_IMPL_CYCLE_COLLECTION_TRACE_END
 
 ScriptLoadRequest::ScriptLoadRequest(ScriptKind aKind,
                                      nsIURI* aURI,
-                                     nsIScriptElement* aElement,
-                                     mozilla::CORSMode aCORSMode,
-                                     const SRIMetadata& aIntegrity,
-                                     nsIURI* aReferrer,
-                                     mozilla::net::ReferrerPolicy aReferrerPolicy)
+                                     ScriptFetchOptions* aFetchOptions,
+                                     const SRIMetadata &aIntegrity,
+                                     nsIURI* aReferrer)
   : mKind(aKind)
-  , mElement(aElement)
-  , mScriptFromHead(false)
+  , mScriptMode(ScriptMode::eBlocking)
   , mProgress(Progress::eLoading)
   , mDataType(DataType::eUnknown)
-  , mScriptMode(ScriptMode::eBlocking)
+  , mScriptFromHead(false)
   , mIsInline(true)
   , mHasSourceMapURL(false)
   , mInDeferList(false)
   , mInAsyncList(false)
   , mIsNonAsyncScriptInserted(false)
   , mIsXSLT(false)
   , mIsCanceled(false)
   , mWasCompiledOMT(false)
   , mIsTracking(false)
+  , mFetchOptions(aFetchOptions)
   , mOffThreadToken(nullptr)
   , mScriptTextLength(0)
   , mScriptBytecode()
   , mBytecodeOffset(0)
   , mURI(aURI)
   , mLineNo(1)
-  , mCORSMode(aCORSMode)
   , mIntegrity(aIntegrity)
   , mReferrer(aReferrer)
-  , mReferrerPolicy(aReferrerPolicy)
 {
+  MOZ_ASSERT(mFetchOptions);
 }
 
 ScriptLoadRequest::~ScriptLoadRequest()
 {
   // We should always clean up any off-thread script parsing resources.
   MOZ_ASSERT(!mOffThreadToken);
 
   // But play it safe in release builds and try to clean them up here
--- a/dom/script/ScriptLoadRequest.h
+++ b/dom/script/ScriptLoadRequest.h
@@ -27,16 +27,43 @@ class ModuleLoadRequest;
 class ScriptLoadRequestList;
 
 enum class ScriptKind {
   eClassic,
   eModule
 };
 
 /*
+ * Some options used when fetching script resources. This only loosely
+ * corresponds to HTML's "script fetch options".
+ *
+ * These are common to all modules in a module graph, and hence a single
+ * instance is shared by all ModuleLoadRequest objects in a graph.
+ */
+
+class ScriptFetchOptions
+{
+  ~ScriptFetchOptions();
+
+public:
+  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(ScriptFetchOptions)
+  NS_DECL_CYCLE_COLLECTION_NATIVE_CLASS(ScriptFetchOptions)
+
+  ScriptFetchOptions(mozilla::CORSMode aCORSMode,
+                     mozilla::net::ReferrerPolicy aReferrerPolicy,
+                     nsIScriptElement* aElement,
+                     nsIPrincipal* aTriggeringPrincipal);
+
+  const mozilla::CORSMode mCORSMode;
+  const mozilla::net::ReferrerPolicy mReferrerPolicy;
+  nsCOMPtr<nsIScriptElement> mElement;
+  nsCOMPtr<nsIPrincipal> mTriggeringPrincipal;
+};
+
+/*
  * A class that handles loading and evaluation of <script> elements.
  */
 
 class ScriptLoadRequest : public nsISupports,
                           private mozilla::LinkedListElement<ScriptLoadRequest>
 {
   typedef LinkedListElement<ScriptLoadRequest> super;
 
@@ -45,46 +72,44 @@ class ScriptLoadRequest : public nsISupp
   friend class ScriptLoadRequestList;
 
 protected:
   virtual ~ScriptLoadRequest();
 
 public:
   ScriptLoadRequest(ScriptKind aKind,
                     nsIURI* aURI,
-                    nsIScriptElement* aElement,
-                    mozilla::CORSMode aCORSMode,
+                    ScriptFetchOptions* aFetchOptions,
                     const SRIMetadata &aIntegrity,
-                    nsIURI* aReferrer,
-                    mozilla::net::ReferrerPolicy aReferrerPolicy);
+                    nsIURI* aReferrer);
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(ScriptLoadRequest)
 
   bool IsModuleRequest() const
   {
     return mKind == ScriptKind::eModule;
   }
 
   ModuleLoadRequest* AsModuleRequest();
 
   void FireScriptAvailable(nsresult aResult)
   {
     bool isInlineClassicScript = mIsInline && !IsModuleRequest();
-    mElement->ScriptAvailable(aResult, mElement, isInlineClassicScript, mURI,
+    Element()->ScriptAvailable(aResult, Element(), isInlineClassicScript, mURI,
                               mLineNo);
   }
   void FireScriptEvaluated(nsresult aResult)
   {
-    mElement->ScriptEvaluated(aResult, mElement, mIsInline);
+    Element()->ScriptEvaluated(aResult, Element(), mIsInline);
   }
 
   bool IsPreload()
   {
-    return mElement == nullptr;
+    return Element() == nullptr;
   }
 
   virtual void Cancel();
 
   bool IsCanceled() const
   {
     return mIsCanceled;
   }
@@ -219,41 +244,68 @@ public:
   }
 
   virtual bool IsTopLevel() const
   {
     // Classic scripts are always top level.
     return true;
   }
 
+  mozilla::CORSMode CORSMode() const
+  {
+    return mFetchOptions->mCORSMode;
+  }
+  mozilla::net::ReferrerPolicy ReferrerPolicy() const
+  {
+    return mFetchOptions->mReferrerPolicy;
+  }
+  nsIScriptElement* Element() const
+  {
+    return mFetchOptions->mElement;
+  }
+  nsIPrincipal* TriggeringPrincipal() const
+  {
+    return mFetchOptions->mTriggeringPrincipal;
+  }
+
+  void SetElement(nsIScriptElement* aElement)
+  {
+    // Called when a preload request is later used for an actual request.
+    MOZ_ASSERT(aElement);
+    MOZ_ASSERT(!Element());
+    mFetchOptions->mElement = aElement;
+  }
+
   bool ShouldAcceptBinASTEncoding() const;
 
   void ClearScriptSource();
 
   void MaybeCancelOffThreadScript();
   void DropBytecodeCacheReferences();
 
   using super::getNext;
   using super::isInList;
 
-  const ScriptKind mKind;
-  nsCOMPtr<nsIScriptElement> mElement;
-  bool mScriptFromHead;   // Synchronous head script block loading of other non js/css content.
+  const ScriptKind mKind; // Whether this is a classic script or a module script.
+  ScriptMode mScriptMode; // Whether this is a blocking, defer or async script.
   Progress mProgress;     // Are we still waiting for a load to complete?
   DataType mDataType;     // Does this contain Source or Bytecode?
-  ScriptMode mScriptMode; // Whether this is a blocking, defer or async script.
+  bool mScriptFromHead;   // Synchronous head script block loading of other non js/css content.
   bool mIsInline;         // Is the script inline or loaded?
   bool mHasSourceMapURL;  // Does the HTTP header have a source map url?
   bool mInDeferList;      // True if we live in mDeferRequests.
   bool mInAsyncList;      // True if we live in mLoadingAsyncRequests or mLoadedAsyncRequests.
   bool mIsNonAsyncScriptInserted; // True if we live in mNonAsyncExternalScriptInsertedRequests
   bool mIsXSLT;           // True if we live in mXSLTRequests.
   bool mIsCanceled;       // True if we have been explicitly canceled.
   bool mWasCompiledOMT;   // True if the script has been compiled off main thread.
   bool mIsTracking;       // True if the script comes from a source on our tracking protection list.
+
+  RefPtr<ScriptFetchOptions> mFetchOptions;
+
   JS::OffThreadToken* mOffThreadToken; // Off-thread parsing token.
   nsString mSourceMapURL; // Holds source map url for loaded scripts
 
   // Holds the top-level JSScript that corresponds to the current source, once
   // it is parsed, and planned to be saved in the bytecode cache.
   JS::Heap<JSScript*> mScript;
 
   // Holds script source data for non-inline scripts. Don't use nsString so we
@@ -266,24 +318,21 @@ public:
   size_t mScriptTextLength;
 
   // Holds the SRI serialized hash and the script bytecode for non-inline
   // scripts.
   mozilla::Vector<uint8_t> mScriptBytecode;
   uint32_t mBytecodeOffset; // Offset of the bytecode in mScriptBytecode
 
   const nsCOMPtr<nsIURI> mURI;
-  nsCOMPtr<nsIPrincipal> mTriggeringPrincipal;
   nsCOMPtr<nsIPrincipal> mOriginPrincipal;
   nsAutoCString mURL;     // Keep the URI's filename alive during off thread parsing.
   int32_t mLineNo;
-  const mozilla::CORSMode mCORSMode;
   const SRIMetadata mIntegrity;
   const nsCOMPtr<nsIURI> mReferrer;
-  const mozilla::net::ReferrerPolicy mReferrerPolicy;
 
   // Holds the Cache information, which is used to register the bytecode
   // on the cache entry, such that we can load it the next time.
   nsCOMPtr<nsICacheInfoChannel> mCacheInfo;
 };
 
 class ScriptLoadRequestList : private mozilla::LinkedList<ScriptLoadRequest>
 {
--- a/dom/script/ScriptLoader.cpp
+++ b/dom/script/ScriptLoader.cpp
@@ -211,17 +211,17 @@ CollectScriptTelemetry(ScriptLoadRequest
 
   // Report the type of source. This is used to monitor the status of the
   // JavaScript Start-up Bytecode Cache, with the expectation of an almost zero
   // source-fallback and alternate-data being roughtly equal to source loads.
   if (aRequest->IsLoadingSource()) {
     if (aRequest->mIsInline) {
       AccumulateCategorical(LABELS_DOM_SCRIPT_LOADING_SOURCE::Inline);
       nsAutoString inlineData;
-      aRequest->mElement->GetScriptText(inlineData);
+      aRequest->Element()->GetScriptText(inlineData);
     } else if (aRequest->IsTextSource()) {
       AccumulateCategorical(LABELS_DOM_SCRIPT_LOADING_SOURCE::SourceFallback);
     }
     // TODO: Add telemetry for BinAST encoded source.
   } else {
     MOZ_ASSERT(aRequest->IsLoading());
     if (aRequest->IsTextSource()) {
       AccumulateCategorical(LABELS_DOM_SCRIPT_LOADING_SOURCE::Source);
@@ -865,17 +865,17 @@ public:
 
 void
 ScriptLoader::ProcessLoadedModuleTree(ModuleLoadRequest* aRequest)
 {
   MOZ_ASSERT(aRequest->IsReadyToRun());
 
   if (aRequest->IsTopLevel()) {
     if (aRequest->mIsInline &&
-        aRequest->mElement->GetParserCreated() == NOT_FROM_PARSER)
+        aRequest->Element()->GetParserCreated() == NOT_FROM_PARSER)
     {
       MOZ_ASSERT(!aRequest->isInList());
       nsContentUtils::AddScriptRunner(
         new ScriptRequestProcessor(this, aRequest));
     } else {
       MaybeMoveToLoadedList(aRequest);
       ProcessPendingRequests();
     }
@@ -955,17 +955,17 @@ ScriptLoader::InstantiateModuleTree(Modu
   return true;
 }
 
 nsresult
 ScriptLoader::RestartLoad(ScriptLoadRequest* aRequest)
 {
   MOZ_ASSERT(aRequest->IsBytecode());
   aRequest->mScriptBytecode.clearAndFree();
-  TRACE_FOR_TEST(aRequest->mElement, "scriptloader_fallback");
+  TRACE_FOR_TEST(aRequest->Element(), "scriptloader_fallback");
 
   // Start a new channel from which we explicitly request to stream the source
   // instead of the bytecode.
   aRequest->mProgress = ScriptLoadRequest::Progress::eLoading_Source;
   nsresult rv = StartLoad(aRequest);
   if (NS_FAILED(rv)) {
     return rv;
   }
@@ -1006,60 +1006,60 @@ ScriptLoader::StartLoad(ScriptLoadReques
       return NS_OK;
     }
   }
 
   nsContentPolicyType contentPolicyType = aRequest->IsPreload()
                                           ? nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD
                                           : nsIContentPolicy::TYPE_INTERNAL_SCRIPT;
   nsCOMPtr<nsINode> context;
-  if (aRequest->mElement) {
-    context = do_QueryInterface(aRequest->mElement);
+  if (aRequest->Element()) {
+    context = do_QueryInterface(aRequest->Element());
   }
   else {
     context = mDocument;
   }
 
   nsCOMPtr<nsILoadGroup> loadGroup = mDocument->GetDocumentLoadGroup();
   nsCOMPtr<nsPIDOMWindowOuter> window = mDocument->GetWindow();
   NS_ENSURE_TRUE(window, NS_ERROR_NULL_POINTER);
   nsIDocShell* docshell = window->GetDocShell();
   nsCOMPtr<nsIInterfaceRequestor> prompter(do_QueryInterface(docshell));
 
   nsSecurityFlags securityFlags;
   if (aRequest->IsModuleRequest()) {
     // According to the spec, module scripts have different behaviour to classic
     // scripts and always use CORS.
     securityFlags = nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS;
-    if (aRequest->mCORSMode == CORS_NONE) {
+    if (aRequest->CORSMode() == CORS_NONE) {
       securityFlags |= nsILoadInfo::SEC_COOKIES_OMIT;
-    } else if (aRequest->mCORSMode == CORS_ANONYMOUS) {
+    } else if (aRequest->CORSMode() == CORS_ANONYMOUS) {
       securityFlags |= nsILoadInfo::SEC_COOKIES_SAME_ORIGIN;
     } else {
-      MOZ_ASSERT(aRequest->mCORSMode == CORS_USE_CREDENTIALS);
+      MOZ_ASSERT(aRequest->CORSMode() == CORS_USE_CREDENTIALS);
       securityFlags |= nsILoadInfo::SEC_COOKIES_INCLUDE;
     }
   } else {
-    securityFlags = aRequest->mCORSMode == CORS_NONE
+    securityFlags = aRequest->CORSMode() == CORS_NONE
       ? nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL
       : nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS;
-    if (aRequest->mCORSMode == CORS_ANONYMOUS) {
+    if (aRequest->CORSMode() == CORS_ANONYMOUS) {
       securityFlags |= nsILoadInfo::SEC_COOKIES_SAME_ORIGIN;
-    } else if (aRequest->mCORSMode == CORS_USE_CREDENTIALS) {
+    } else if (aRequest->CORSMode() == CORS_USE_CREDENTIALS) {
       securityFlags |= nsILoadInfo::SEC_COOKIES_INCLUDE;
     }
   }
   securityFlags |= nsILoadInfo::SEC_ALLOW_CHROME;
 
   nsCOMPtr<nsIChannel> channel;
   nsresult rv = NS_NewChannelWithTriggeringPrincipal(
       getter_AddRefs(channel),
       aRequest->mURI,
       context,
-      aRequest->mTriggeringPrincipal,
+      aRequest->TriggeringPrincipal(),
       securityFlags,
       contentPolicyType,
       nullptr, // aPerformanceStorage
       loadGroup,
       prompter,
       nsIRequest::LOAD_NORMAL |
       nsIChannel::LOAD_CLASSIFY_URI);
 
@@ -1129,17 +1129,17 @@ ScriptLoader::StartLoad(ScriptLoadReques
     if (BinASTEncodingEnabled() && aRequest->ShouldAcceptBinASTEncoding()) {
       acceptTypes = APPLICATION_JAVASCRIPT_BINAST ", */*";
     }
     rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"),
                                        acceptTypes, false);
     MOZ_ASSERT(NS_SUCCEEDED(rv));
 
     rv = httpChannel->SetReferrerWithPolicy(aRequest->mReferrer,
-                                            aRequest->mReferrerPolicy);
+                                            aRequest->ReferrerPolicy());
     MOZ_ASSERT(NS_SUCCEEDED(rv));
 
     nsCOMPtr<nsIHttpChannelInternal> internalChannel(do_QueryInterface(httpChannel));
     if (internalChannel) {
       rv = internalChannel->SetIntegrityMetadata(aRequest->mIntegrity.GetIntegrityString());
       MOZ_ASSERT(NS_SUCCEEDED(rv));
     }
   }
@@ -1221,30 +1221,31 @@ CSPAllowsInlineScript(nsIScriptElement* 
                             &allowInlineScript);
   return allowInlineScript;
 }
 
 ScriptLoadRequest*
 ScriptLoader::CreateLoadRequest(ScriptKind aKind,
                                 nsIURI* aURI,
                                 nsIScriptElement* aElement,
+                                nsIPrincipal* aTriggeringPrincipal,
                                 CORSMode aCORSMode,
                                 const SRIMetadata& aIntegrity,
                                 mozilla::net::ReferrerPolicy aReferrerPolicy)
 {
   nsIURI* referrer = mDocument->GetDocumentURI();
+  ScriptFetchOptions* fetchOptions =
+    new ScriptFetchOptions(aCORSMode, aReferrerPolicy, aElement, aTriggeringPrincipal);
 
   if (aKind == ScriptKind::eClassic) {
-    return new ScriptLoadRequest(aKind, aURI, aElement, aCORSMode, aIntegrity,
-                                 referrer, aReferrerPolicy);
+    return new ScriptLoadRequest(aKind, aURI, fetchOptions, aIntegrity, referrer);
   }
 
   MOZ_ASSERT(aKind == ScriptKind::eModule);
-  return new ModuleLoadRequest(aURI, aElement, aCORSMode, aIntegrity, referrer,
-                               aReferrerPolicy, this);
+  return new ModuleLoadRequest(aURI, fetchOptions, aIntegrity, referrer, this);
 }
 
 bool
 ScriptLoader::ProcessScriptElement(nsIScriptElement* aElement)
 {
   // We need a document to evaluate scripts.
   NS_ENSURE_TRUE(mDocument, false);
 
@@ -1375,19 +1376,18 @@ ScriptLoader::ProcessExternalScript(nsIS
 
     nsCOMPtr<nsIPrincipal> principal = aElement->GetScriptURITriggeringPrincipal();
     if (!principal) {
       principal = aScriptContent->NodePrincipal();
     }
 
     CORSMode ourCORSMode = aElement->GetCORSMode();
     mozilla::net::ReferrerPolicy ourRefPolicy = mDocument->GetReferrerPolicy();
-    request = CreateLoadRequest(aScriptKind, scriptURI, aElement,
+    request = CreateLoadRequest(aScriptKind, scriptURI, aElement, principal,
                                 ourCORSMode, sriMetadata, ourRefPolicy);
-    request->mTriggeringPrincipal = std::move(principal);
     request->mIsInline = false;
     request->SetScriptMode(aElement->GetScriptDeferred(),
                            aElement->GetScriptAsync());
     // keep request->mScriptFromHead to false so we don't treat non preloaded
     // scripts as blockers for full page load. See bug 792438.
 
     LOG(("ScriptLoadRequest (%p): Created request for external script",
          request.get()));
@@ -1516,25 +1516,25 @@ ScriptLoader::ProcessInlineScript(nsIScr
   // Inline classic scripts ignore their CORS mode and are always CORS_NONE.
   CORSMode corsMode = CORS_NONE;
   if (aScriptKind == ScriptKind::eModule) {
     corsMode = aElement->GetCORSMode();
   }
 
   RefPtr<ScriptLoadRequest> request =
     CreateLoadRequest(aScriptKind, mDocument->GetDocumentURI(), aElement,
+                      mDocument->NodePrincipal(),
                       corsMode,
                       SRIMetadata(), // SRI doesn't apply
                       mDocument->GetReferrerPolicy());
   request->mIsInline = true;
-  request->mTriggeringPrincipal = mDocument->NodePrincipal();
   request->mLineNo = aElement->GetScriptLineNumber();
   request->mProgress = ScriptLoadRequest::Progress::eLoading_Source;
   request->SetTextSource();
-  TRACE_FOR_TEST_BOOL(request->mElement, "scriptloader_load_source");
+  TRACE_FOR_TEST_BOOL(request->Element(), "scriptloader_load_source");
   CollectScriptTelemetry(request);
 
   // Only the 'async' attribute is heeded on an inline module script and
   // inline classic scripts ignore both these attributes.
   MOZ_ASSERT(!aElement->GetScriptDeferred());
   MOZ_ASSERT_IF(!request->IsModuleRequest(), !aElement->GetScriptAsync());
   request->SetScriptMode(false, aElement->GetScriptAsync());
 
@@ -1609,27 +1609,27 @@ ScriptLoader::LookupPreloadRequest(nsISc
     mPreloads.IndexOf(aElement->GetScriptURI(), 0, PreloadURIComparator());
   if (i == nsTArray<PreloadInfo>::NoIndex) {
     return nullptr;
   }
 
   // Found preloaded request. Note that a script-inserted script can steal a
   // preload!
   RefPtr<ScriptLoadRequest> request = mPreloads[i].mRequest;
-  request->mElement = aElement;
+  request->SetElement(aElement);
   nsString preloadCharset(mPreloads[i].mCharset);
   mPreloads.RemoveElementAt(i);
 
   // Double-check that the charset the preload used is the same as the charset
   // we have now.
   nsAutoString elementCharset;
   aElement->GetScriptCharset(elementCharset);
   if (!elementCharset.Equals(preloadCharset) ||
-      aElement->GetCORSMode() != request->mCORSMode ||
-      mDocument->GetReferrerPolicy() != request->mReferrerPolicy ||
+      aElement->GetCORSMode() != request->CORSMode() ||
+      mDocument->GetReferrerPolicy() != request->ReferrerPolicy() ||
       aScriptKind != request->mKind) {
     // Drop the preload.
     request->Cancel();
     AccumulateCategorical(LABELS_DOM_SCRIPT_PRELOAD_RESULT::RequestMismatch);
     return nullptr;
   }
 
   return request;
@@ -1900,17 +1900,17 @@ SourceBufferHolder
 ScriptLoader::GetScriptSource(JSContext* aCx, ScriptLoadRequest* aRequest)
 {
   // Return a SourceBufferHolder object holding the script's source text.
   // Ownership of the buffer is transferred to the resulting SourceBufferHolder.
 
   // If there's no script text, we try to get it from the element
   if (aRequest->mIsInline) {
     nsAutoString inlineData;
-    aRequest->mElement->GetScriptText(inlineData);
+    aRequest->Element()->GetScriptText(inlineData);
 
     size_t nbytes = inlineData.Length() * sizeof(char16_t);
     JS::UniqueTwoByteChars chars(static_cast<char16_t*>(JS_malloc(aCx, nbytes)));
     MOZ_RELEASE_ASSERT(chars);
     memcpy(chars.get(), inlineData.get(), nbytes);
     return SourceBufferHolder(std::move(chars), inlineData.Length());
   }
 
@@ -1943,31 +1943,31 @@ ScriptLoader::ProcessRequest(ScriptLoadR
     if (!request->mModuleScript) {
       // There was an error fetching a module script.  Nothing to do here.
       LOG(("ScriptLoadRequest (%p):   Error loading request, firing error", aRequest));
       FireScriptAvailable(NS_ERROR_FAILURE, aRequest);
       return NS_OK;
     }
   }
 
-  nsCOMPtr<nsINode> scriptElem = do_QueryInterface(aRequest->mElement);
+  nsCOMPtr<nsINode> scriptElem = do_QueryInterface(aRequest->Element());
 
   nsCOMPtr<nsIDocument> doc;
   if (!aRequest->mIsInline) {
     doc = scriptElem->OwnerDoc();
   }
 
   nsCOMPtr<nsIScriptElement> oldParserInsertedScript;
-  uint32_t parserCreated = aRequest->mElement->GetParserCreated();
+  uint32_t parserCreated = aRequest->Element()->GetParserCreated();
   if (parserCreated) {
     oldParserInsertedScript = mCurrentParserInsertedScript;
-    mCurrentParserInsertedScript = aRequest->mElement;
+    mCurrentParserInsertedScript = aRequest->Element();
   }
 
-  aRequest->mElement->BeginEvaluating();
+  aRequest->Element()->BeginEvaluating();
 
   FireScriptAvailable(NS_OK, aRequest);
 
   // The window may have gone away by this point, in which case there's no point
   // in trying to run the script.
 
   {
     // Try to perform a microtask checkpoint
@@ -2002,17 +2002,17 @@ ScriptLoader::ProcessRequest(ScriptLoadR
     nsContentUtils::DispatchTrustedEvent(scriptElem->OwnerDoc(),
                                          scriptElem,
                                          NS_LITERAL_STRING("afterscriptexecute"),
                                          CanBubble::eYes, Cancelable::eNo);
   }
 
   FireScriptEvaluated(rv, aRequest);
 
-  aRequest->mElement->EndEvaluating();
+  aRequest->Element()->EndEvaluating();
 
   if (parserCreated) {
     mCurrentParserInsertedScript = oldParserInsertedScript;
   }
 
   if (aRequest->mOffThreadToken) {
     // The request was parsed off-main-thread, but the result of the off
     // thread parse was not actually needed to process the request
@@ -2036,31 +2036,31 @@ ScriptLoader::ProcessRequest(ScriptLoadR
 }
 
 void
 ScriptLoader::FireScriptAvailable(nsresult aResult,
                                   ScriptLoadRequest* aRequest)
 {
   for (int32_t i = 0; i < mObservers.Count(); i++) {
     nsCOMPtr<nsIScriptLoaderObserver> obs = mObservers[i];
-    obs->ScriptAvailable(aResult, aRequest->mElement,
+    obs->ScriptAvailable(aResult, aRequest->Element(),
                          aRequest->mIsInline, aRequest->mURI,
                          aRequest->mLineNo);
   }
 
   aRequest->FireScriptAvailable(aResult);
 }
 
 void
 ScriptLoader::FireScriptEvaluated(nsresult aResult,
                                   ScriptLoadRequest* aRequest)
 {
   for (int32_t i = 0; i < mObservers.Count(); i++) {
     nsCOMPtr<nsIScriptLoaderObserver> obs = mObservers[i];
-    obs->ScriptEvaluated(aResult, aRequest->mElement,
+    obs->ScriptEvaluated(aResult, aRequest->Element(),
                          aRequest->mIsInline);
   }
 
   aRequest->FireScriptEvaluated(aResult);
 }
 
 already_AddRefed<nsIScriptGlobalObject>
 ScriptLoader::GetScriptGlobalObject()
@@ -2121,18 +2121,18 @@ ScriptLoader::FillCompileOptionsForReque
     aOptions->setMutedErrors(!subsumes);
   }
 
   if (aRequest->IsModuleRequest()) {
     aOptions->hideScriptFromDebugger = true;
   } else {
     JSContext* cx = jsapi.cx();
     JS::Rooted<JS::Value> elementVal(cx);
-    MOZ_ASSERT(aRequest->mElement);
-    if (NS_SUCCEEDED(nsContentUtils::WrapNative(cx, aRequest->mElement,
+    MOZ_ASSERT(aRequest->Element());
+    if (NS_SUCCEEDED(nsContentUtils::WrapNative(cx, aRequest->Element(),
                                                 &elementVal,
                                                 /* aAllowWrapping = */ true))) {
       MOZ_ASSERT(elementVal.isObject());
       aOptions->setElement(&elementVal.toObject());
     }
   }
 
   return NS_OK;
@@ -2235,17 +2235,17 @@ ScriptLoader::EvaluateScript(ScriptLoadR
   using namespace mozilla::Telemetry;
   MOZ_ASSERT(aRequest->IsReadyToRun());
 
   // We need a document to evaluate scripts.
   if (!mDocument) {
     return NS_ERROR_FAILURE;
   }
 
-  nsCOMPtr<nsIContent> scriptContent(do_QueryInterface(aRequest->mElement));
+  nsCOMPtr<nsIContent> scriptContent(do_QueryInterface(aRequest->Element()));
   nsIDocument* ownerDoc = scriptContent->OwnerDoc();
   if (ownerDoc != mDocument) {
     // Willful violation of HTML5 as of 2010-12-01
     return NS_ERROR_FAILURE;
   }
 
   // Get the script-type to be used by this element.
   NS_ASSERTION(scriptContent, "no content - what is default script-type?");
@@ -2296,17 +2296,17 @@ ScriptLoader::EvaluateScript(ScriptLoadR
         JS_SetPendingException(cx, error);
         return NS_OK; // An error is reported by AutoEntryScript.
       }
 
       JS::Rooted<JSObject*> module(cx, moduleScript->ModuleRecord());
       MOZ_ASSERT(module);
 
       if (!moduleScript->SourceElementAssociated()) {
-        rv = nsJSUtils::InitModuleSourceElement(cx, module, aRequest->mElement);
+        rv = nsJSUtils::InitModuleSourceElement(cx, module, aRequest->Element());
         NS_ENSURE_SUCCESS(rv, rv);
         moduleScript->SetSourceElementAssociated();
 
         // The script is now ready to be exposed to the debugger.
         JS::Rooted<JSScript*> script(cx, JS::GetModuleScript(module));
         JS::ExposeScriptToDebugger(cx, script);
       }
 
@@ -2315,24 +2315,24 @@ ScriptLoader::EvaluateScript(ScriptLoadR
       if (NS_FAILED(rv)) {
         LOG(("ScriptLoadRequest (%p):   evaluation failed", aRequest));
         rv = NS_OK; // An error is reported by AutoEntryScript.
       }
 
       aRequest->mCacheInfo = nullptr;
     } else {
       // Update our current script.
-      AutoCurrentScriptUpdater scriptUpdater(this, aRequest->mElement);
+      AutoCurrentScriptUpdater scriptUpdater(this, aRequest->Element());
 
       JS::CompileOptions options(cx);
       rv = FillCompileOptionsForRequest(aes, aRequest, global, &options);
 
       if (NS_SUCCEEDED(rv)) {
         if (aRequest->IsBytecode()) {
-          TRACE_FOR_TEST(aRequest->mElement, "scriptloader_execute");
+          TRACE_FOR_TEST(aRequest->Element(), "scriptloader_execute");
           nsJSUtils::ExecutionContext exec(cx, global);
           if (aRequest->mOffThreadToken) {
             LOG(("ScriptLoadRequest (%p): Decode Bytecode & Join and Execute", aRequest));
             rv = exec.DecodeJoinAndExec(&aRequest->mOffThreadToken);
           } else {
             LOG(("ScriptLoadRequest (%p): Decode Bytecode and Execute", aRequest));
             rv = exec.DecodeAndExec(options, aRequest->mScriptBytecode,
                                     aRequest->mBytecodeOffset);
@@ -2343,17 +2343,17 @@ ScriptLoader::EvaluateScript(ScriptLoadR
         } else {
           MOZ_ASSERT(aRequest->IsSource());
           JS::Rooted<JSScript*> script(cx);
           bool encodeBytecode = ShouldCacheBytecode(aRequest);
 
           {
             nsJSUtils::ExecutionContext exec(cx, global);
             exec.SetEncodeBytecode(encodeBytecode);
-            TRACE_FOR_TEST(aRequest->mElement, "scriptloader_execute");
+            TRACE_FOR_TEST(aRequest->Element(), "scriptloader_execute");
             if (aRequest->mOffThreadToken) {
               // Off-main-thread parsing.
               LOG(("ScriptLoadRequest (%p): Join (off-thread parsing) and Execute",
                    aRequest));
               if (aRequest->IsBinASTSource()) {
                 rv = exec.DecodeBinASTJoinAndExec(&aRequest->mOffThreadToken, &script);
               } else {
                 MOZ_ASSERT(aRequest->IsTextSource());
@@ -2380,23 +2380,23 @@ ScriptLoader::EvaluateScript(ScriptLoadR
               }
             }
           }
 
           // Queue the current script load request to later save the bytecode.
           if (script && encodeBytecode) {
             aRequest->mScript = script;
             HoldJSObjects(aRequest);
-            TRACE_FOR_TEST(aRequest->mElement, "scriptloader_encode");
+            TRACE_FOR_TEST(aRequest->Element(), "scriptloader_encode");
             MOZ_ASSERT(aRequest->mBytecodeOffset == aRequest->mScriptBytecode.length());
             RegisterForBytecodeEncoding(aRequest);
           } else {
             LOG(("ScriptLoadRequest (%p): Bytecode-cache: disabled (rv = %X, script = %p)",
                  aRequest, unsigned(rv), script.get()));
-            TRACE_FOR_TEST_NONE(aRequest->mElement, "scriptloader_no_encode");
+            TRACE_FOR_TEST_NONE(aRequest->Element(), "scriptloader_no_encode");
             aRequest->mCacheInfo = nullptr;
           }
         }
       }
     }
 
     // Even if we are not saving the bytecode of the current script, we have
     // to trigger the encoding of the bytecode, as the current script can
@@ -2507,17 +2507,17 @@ ScriptLoader::EncodeBytecode()
 
 void
 ScriptLoader::EncodeRequestBytecode(JSContext* aCx, ScriptLoadRequest* aRequest)
 {
   using namespace mozilla::Telemetry;
   nsresult rv = NS_OK;
   MOZ_ASSERT(aRequest->mCacheInfo);
   auto bytecodeFailed = mozilla::MakeScopeExit([&]() {
-    TRACE_FOR_TEST_NONE(aRequest->mElement, "scriptloader_bytecode_failed");
+    TRACE_FOR_TEST_NONE(aRequest->Element(), "scriptloader_bytecode_failed");
   });
 
   JS::RootedScript script(aCx, aRequest->mScript);
   if (!JS::FinishIncrementalEncoding(aCx, script, aRequest->mScriptBytecode)) {
     LOG(("ScriptLoadRequest (%p): Cannot serialize bytecode",
          aRequest));
     return;
   }
@@ -2552,17 +2552,17 @@ ScriptLoader::EncodeRequestBytecode(JSCo
                      aRequest->mScriptBytecode.length(), &n);
   LOG(("ScriptLoadRequest (%p): Write bytecode cache (rv = %X, length = %u, written = %u)",
        aRequest, unsigned(rv), unsigned(aRequest->mScriptBytecode.length()), n));
   if (NS_FAILED(rv)) {
     return;
   }
 
   bytecodeFailed.release();
-  TRACE_FOR_TEST_NONE(aRequest->mElement, "scriptloader_bytecode_saved");
+  TRACE_FOR_TEST_NONE(aRequest->Element(), "scriptloader_bytecode_saved");
 }
 
 void
 ScriptLoader::GiveUpBytecodeEncoding()
 {
   // If the document went away prematurely, we still want to set this, in order
   // to avoid queuing more scripts.
   mGiveUpEncoding = true;
@@ -2579,17 +2579,17 @@ ScriptLoader::GiveUpBytecodeEncoding()
     if (context) {
       aes.emplace(globalObject, "give-up bytecode encoding", true);
     }
   }
 
   while (!mBytecodeEncodingQueue.isEmpty()) {
     RefPtr<ScriptLoadRequest> request = mBytecodeEncodingQueue.StealFirst();
     LOG(("ScriptLoadRequest (%p): Cannot serialize bytecode", request.get()));
-    TRACE_FOR_TEST_NONE(request->mElement, "scriptloader_bytecode_failed");
+    TRACE_FOR_TEST_NONE(request->Element(), "scriptloader_bytecode_failed");
 
     if (aes.isSome()) {
       JS::RootedScript script(aes->cx(), request->mScript);
       Unused << JS::FinishIncrementalEncoding(aes->cx(), script,
                                               request->mScriptBytecode);
     }
 
     request->mScriptBytecode.clearAndFree();
@@ -2887,18 +2887,18 @@ ScriptLoader::VerifySRI(ScriptLoadReques
 
     if (loadInfo && loadInfo->GetEnforceSRI()) {
       MOZ_LOG(SRILogHelper::GetSriLog(), mozilla::LogLevel::Debug,
               ("ScriptLoader::OnStreamComplete, required SRI not found"));
       nsCOMPtr<nsIContentSecurityPolicy> csp;
       loadInfo->LoadingPrincipal()->GetCsp(getter_AddRefs(csp));
       nsAutoCString violationURISpec;
       mDocument->GetDocumentURI()->GetAsciiSpec(violationURISpec);
-      uint32_t lineNo = aRequest->mElement ? aRequest->mElement->GetScriptLineNumber() : 0;
-      uint32_t columnNo = aRequest->mElement ? aRequest->mElement->GetScriptColumnNumber() : 0;
+      uint32_t lineNo = aRequest->Element() ? aRequest->Element()->GetScriptLineNumber() : 0;
+      uint32_t columnNo = aRequest->Element() ? aRequest->Element()->GetScriptColumnNumber() : 0;
       csp->LogViolationDetails(
         nsIContentSecurityPolicy::VIOLATION_TYPE_REQUIRE_SRI_FOR_SCRIPT,
         nullptr, // triggering element
         NS_ConvertUTF8toUTF16(violationURISpec),
         EmptyString(), lineNo, columnNo, EmptyString(), EmptyString());
       rv = NS_ERROR_SRI_CORRUPT;
     }
   }
@@ -2953,17 +2953,17 @@ ScriptLoader::SaveSRIHash(ScriptLoadRequ
 }
 
 void
 ScriptLoader::ReportErrorToConsole(ScriptLoadRequest *aRequest,
                                    nsresult aResult) const
 {
   MOZ_ASSERT(aRequest);
 
-  if (!aRequest->mElement) {
+  if (!aRequest->Element()) {
     return;
   }
 
   bool isScript = !aRequest->IsModuleRequest();
   const char* message;
   if (aResult == NS_ERROR_MALFORMED_URI) {
     message =
       isScript ? "ScriptSourceMalformed" : "ModuleSourceMalformed";
@@ -2974,18 +2974,18 @@ ScriptLoader::ReportErrorToConsole(Scrip
   } else {
     message =
       isScript ? "ScriptSourceLoadFailed" : "ModuleSourceLoadFailed";
   }
 
   NS_ConvertUTF8toUTF16 url(aRequest->mURI->GetSpecOrDefault());
   const char16_t* params[] = { url.get() };
 
-  uint32_t lineNo = aRequest->mElement->GetScriptLineNumber();
-  uint32_t columnNo = aRequest->mElement->GetScriptColumnNumber();
+  uint32_t lineNo = aRequest->Element()->GetScriptLineNumber();
+  uint32_t columnNo = aRequest->Element()->GetScriptColumnNumber();
 
   nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
                                   NS_LITERAL_CSTRING("Script Loader"), mDocument,
                                   nsContentUtils::eDOM_PROPERTIES, message,
                                   params, ArrayLength(params), nullptr,
                                   EmptyString(), lineNo, columnNo);
 }
 
@@ -2993,17 +2993,17 @@ void
 ScriptLoader::HandleLoadError(ScriptLoadRequest *aRequest, nsresult aResult)
 {
   /*
    * Handle script not loading error because source was a tracking URL.
    * We make a note of this script node by including it in a dedicated
    * array of blocked tracking nodes under its parent document.
    */
   if (aResult == NS_ERROR_TRACKING_URI) {
-    nsCOMPtr<nsIContent> cont = do_QueryInterface(aRequest->mElement);
+    nsCOMPtr<nsIContent> cont = do_QueryInterface(aRequest->Element());
     mDocument->AddBlockedTrackingNode(cont);
   }
 
   if (aRequest->IsModuleRequest() && !aRequest->mIsInline) {
     auto request = aRequest->AsModuleRequest();
     SetModuleFetchFinishedAndResumeWaitingRequests(request, aResult);
   }
 
@@ -3038,22 +3038,22 @@ ScriptLoader::HandleLoadError(ScriptLoad
     MOZ_ASSERT(!modReq->isInList());
     modReq->Cancel();
     // A single error is fired for the top level module.
   } else if (mParserBlockingRequest == aRequest) {
     MOZ_ASSERT(!aRequest->isInList());
     mParserBlockingRequest = nullptr;
     UnblockParser(aRequest);
 
-    // Ensure that we treat aRequest->mElement as our current parser-inserted
+    // Ensure that we treat aRequest->Element() as our current parser-inserted
     // script while firing onerror on it.
-    MOZ_ASSERT(aRequest->mElement->GetParserCreated());
+    MOZ_ASSERT(aRequest->Element()->GetParserCreated());
     nsCOMPtr<nsIScriptElement> oldParserInsertedScript =
       mCurrentParserInsertedScript;
-    mCurrentParserInsertedScript = aRequest->mElement;
+    mCurrentParserInsertedScript = aRequest->Element();
     FireScriptAvailable(aResult, aRequest);
     ContinueParserAsync(aRequest);
     mCurrentParserInsertedScript = oldParserInsertedScript;
   } else if (aRequest->IsPreload()) {
     if (aRequest->IsModuleRequest()) {
       aRequest->Cancel();
     }
     if (aRequest->IsTopLevel()) {
@@ -3066,23 +3066,23 @@ ScriptLoader::HandleLoadError(ScriptLoad
     MOZ_ASSERT(aRequest->IsCanceled());
     MOZ_ASSERT(!aRequest->isInList());
   }
 }
 
 void
 ScriptLoader::UnblockParser(ScriptLoadRequest* aParserBlockingRequest)
 {
-  aParserBlockingRequest->mElement->UnblockParser();
+  aParserBlockingRequest->Element()->UnblockParser();
 }
 
 void
 ScriptLoader::ContinueParserAsync(ScriptLoadRequest* aParserBlockingRequest)
 {
-  aParserBlockingRequest->mElement->ContinueParserAsync();
+  aParserBlockingRequest->Element()->ContinueParserAsync();
 }
 
 uint32_t
 ScriptLoader::NumberOfProcessors()
 {
   if (mNumberOfProcessors > 0)
     return mNumberOfProcessors;
 
@@ -3153,17 +3153,17 @@ ScriptLoader::PrepareLoadedRequest(Scrip
       aRequest->SetIsTracking();
     }
   }
 
   nsCOMPtr<nsIChannel> channel = do_QueryInterface(req);
   // If this load was subject to a CORS check, don't flag it with a separate
   // origin principal, so that it will treat our document's principal as the
   // origin principal.  Module loads always use CORS.
-  if (!aRequest->IsModuleRequest() && aRequest->mCORSMode == CORS_NONE) {
+  if (!aRequest->IsModuleRequest() && aRequest->CORSMode() == CORS_NONE) {
     rv = nsContentUtils::GetSecurityManager()->
       GetChannelResultPrincipal(channel, getter_AddRefs(aRequest->mOriginPrincipal));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // This assertion could fire errorously if we ran out of memory when
   // inserting the request in the array. However it's an unlikely case
   // so if you see this assertion it is likely something else that is
@@ -3307,19 +3307,19 @@ ScriptLoader::PreloadURI(nsIURI* aURI,
     return;
   }
 
   SRIMetadata sriMetadata;
   GetSRIMetadata(aIntegrity, &sriMetadata);
 
   RefPtr<ScriptLoadRequest> request =
     CreateLoadRequest(scriptKind, aURI, nullptr,
+                      mDocument->NodePrincipal(),
                       Element::StringToCORSMode(aCrossOrigin), sriMetadata,
                       aReferrerPolicy);
-  request->mTriggeringPrincipal = mDocument->NodePrincipal();
   request->mIsInline = false;
   request->mScriptFromHead = aScriptFromHead;
   request->SetScriptMode(aDefer, aAsync);
 
   if (LOG_ENABLED()) {
     nsAutoCString url;
     aURI->GetAsciiSpec(url);
     LOG(("ScriptLoadRequest (%p): Created preload request for %s",
--- a/dom/script/ScriptLoader.h
+++ b/dom/script/ScriptLoader.h
@@ -344,16 +344,17 @@ public:
   }
 
 private:
   virtual ~ScriptLoader();
 
   ScriptLoadRequest* CreateLoadRequest(ScriptKind aKind,
                                        nsIURI* aURI,
                                        nsIScriptElement* aElement,
+                                       nsIPrincipal* aTriggeringPrincipal,
                                        mozilla::CORSMode aCORSMode,
                                        const SRIMetadata& aIntegrity,
                                        mozilla::net::ReferrerPolicy aReferrerPolicy);
 
   /**
    * Unblocks the creator parser of the parser-blocking scripts.
    */
   void UnblockParser(ScriptLoadRequest* aParserBlockingRequest);