rstacruz / nprogress

For slim progress bars like on YouTube, Medium, etc
http://ricostacruz.com/nprogress
MIT License
25.98k stars 1.81k forks source link

Add checks on component setup to avoid runtime errors #246

Open bombillazo opened 1 year ago

bombillazo commented 1 year ago

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch nprogress@0.2.0 for the project I'm working on.

Sometimes the component failed to load since not all conditions to handle the component are met. These changes add checks to avoid runtime errors.

Here is the diff that solved my problem:

diff --git a/node_modules/nprogress/nprogress.js b/node_modules/nprogress/nprogress.js
index b23b300..d99e2d6 100644
--- a/node_modules/nprogress/nprogress.js
+++ b/node_modules/nprogress/nprogress.js
@@ -240,11 +240,14 @@
       spinner && removeElement(spinner);
     }

+    if(!parent){
+      parent   = document.querySelector('body')
+    }
+
     if (parent != document.body) {
       addClass(parent, 'nprogress-custom-parent');
     }
-
-    parent.appendChild(progress);
+    parent?.appendChild(progress);
     return progress;
   };

@@ -433,7 +436,8 @@
     if (hasClass(oldList, name)) return; 

     // Trim the opening space.
-    element.className = newList.substring(1);
+    if(element)
+      element.className = newList.substring(1);
   }

   /**
@@ -460,7 +464,7 @@
    */

   function classList(element) {
-    return (' ' + (element.className || '') + ' ').replace(/\s+/gi, ' ');
+    return (' ' + (element?.className || '') + ' ').replace(/\s+/gi, ' ');
   }

   /**

This issue body was partially generated by patch-package.