avatarDr. Derek Austin 🥳

Summary

The web content provides an in-depth guide on how to load external JavaScript files directly from the browser's developer console using various methods such as document.write(), appendChild(), and fetch().

Abstract

The article titled "WEB DEVELOPER CONSOLE TRICKS" delves into the techniques for importing external JavaScript files into a webpage through the browser console. It explains the limitations of using document.write() due to its tendency to overwrite the current document, and contrasts this with the more practical appendChild() method, which safely adds a script tag to the page without clearing existing content. Additionally, the article explores the use of the fetch() API, both with and without async/await syntax, to dynamically load scripts. The author emphasizes the security risks associated with eval() and recommends using Function() as a safer alternative. The article also touches on other tools and libraries like jQuery's $.getScript(), SystemJS, ModuleLoader, jspm.io, Tampermonkey, RunKit, and CodeSandbox for loading external scripts. It concludes with a discussion on namespace pollution and provides further reading resources for developers interested in mastering the art of loading external JavaScript resources.

Opinions

  • The author suggests that using document.write() is not ideal for loading external scripts as it can clear the current document.
  • appendChild() is presented as a superior method for loading scripts without disrupting the existing page content.
  • The use of eval() is discouraged due to security concerns, with Function() being recommended as a safer alternative.
  • The article promotes the fetch() API as a modern approach to loading external scripts, highlighting its flexibility with both Promise chaining and async/await syntax.
  • The author acknowledges the potential for namespace conflicts when importing external libraries, particularly with jQuery's dollar sign $() method.
  • Tools like Tampermonkey and RunKit are endorsed for developers who need to manage multiple scripts on a page without causing namespace collisions.
  • The article encourages the exploration of additional resources and tools for developers to enhance their understanding and capabilities in loading external JavaScript files.

WEB DEVELOPER CONSOLE TRICKS

How to Load External JavaScript Files From the Browser Console

Loading an external script directly from the console can be tricky. Here is how to import JavaScript without a <script> tag directly from Firefox or Chrome’s development console.

Photo by Elly Johnson on Unsplash

Let’s say you’re working on a project, and you are considering adding an external library to manipulate the page or add additional functionality. You might want to load up the latest version of jQuery, for example.

Usually, you would just add a pt> tag to the HTML, which will load the external JavaScript file. For example, to load jQuery, you would add:

View the raw code as a GitHub gist

But what if you want to just load the external script using the command line from the DevTools console? Doing so is especially useful when prototyping or when you are trying to tweak pages that you don’t own — like if you want to use jQuery to quickly process data on someone else’s site.

This article will explain how you can load an external JavaScript file directly from the browser’s console window as part of your prototyping workflow.

You don’t need to know jQuery or any other external library in order to be able to use the methods discussed in this article. Thankfully, JavaScript has built-in tools to import external JavaScript files from the console.

The quick & dirty way

The shortest and most-straightforward way to import an external script file from the console is to use document.write(), literally writing the <script> tag to the loaded page. Here is a code example:

View the raw code as a GitHub gist

Note the use of template literals for the HTML in the code snippet.

This method will work fine if you just need the script to work in the console, but it is no good if you want to work with the currently open document — the current page will disappear instantly as soon as you run this code.

Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.” — MDN Docs

Let’s explore two other options that won’t clear the loaded document.

A better way

Using appendChild() is a more useful way to load an external script file. Instead of overwriting the loaded page with document.write(), appendChild() will add a new <script> tag directly to the page.

Let’s take a look at a code example:

View the raw code as a GitHub gist

Note the use of eval() to execute the code is not needed in most instances. You actually only need eval() if your code is a string containing the <script> tag, like in the document.write() example:

eval(`<script src="script.js" type="text/javascript"`>

If you have a string containing the <script> tag loading the file, the string won’t actually be run without eval(). But if your script is an external JavaScript file (like loading jQuery, as we’ll see later), you don’t need eval(). Just callingNode.appendChild(script) will load the script for you.

You should be aware that eval() has some security risks. I’ll explain later why you would use Function() instead, but for demonstration purposes eval() will work fine. Using eval() to evaluate a string is similar to doing so with document.write(): something you can do, but shouldn’t.

Since I included eval() in the examples for comparison and discussion, please be aware that it’s not necessary in modern browsers.

Another way: fetch

Using fetch() is going to be another way to load an external JavaScript file from the command line.

Here is an example of using fetch() with multiple .then() calls:

View the raw code as a GitHub gist

Alternatively, you can achieve the same functionality using async / await instead of chaining the Promise returned by fetch():

View the raw code as a GitHub gist

Again, you probably want to substitute Function() for eval() if you need to evaluate a string, as I will be discussing later in the article. That will only apply if you’re loading a string that includes a <script> tag that needs to be executed; otherwise, you don’t need either command.

Next, let’s look at a working example of each method using jQuery.

Loading jQuery in the console

This section will provide code examples for each method discussed above. You will be loading the jQuery library and then using it to apply a CSS border style to every iv> element on the page.

Please be aware that you might get a TypeError$(...).css is not a function” with any of these examples if you enter all the commands at the same time. You need to wait for a second between loading the script and actually using it. So enter the commands necessary to load the external script first, then enter commands using the script.

The TypeError occurs because JavaScript actually has a built-in dollar sign method $() that you are trying to overwrite with jQuery. The built-in dollar sign method does not have a .css() function — that’s jQuery. So you have to wait for eval() to finish loading the script before you can actually call the $("div").css() function.

Finally, these demonstrations may only work on certain pages: for me, they work in the browser console on the Google homepage, but not while looking at a GitHub Gist, because of the message:

Refused to load the script 'https://code.jquery.com/jquery-3.5.0.js' because it violates the following Content Security Policy directive: "script-src github.githubassets.com".

Your mileage may vary.

Method 1: document.write()

View the raw code as a GitHub gist

In this case, document.write() overwrites the loaded page, so there is nothing to actually apply the CSS styles to. But, jQuery will be loaded into the console window, for what it’s worth.

Method 2: appendChild()

View the raw code as a GitHub gist

This method works great, without overwriting the loaded page. Calling document.head.appendChild(script) loads the script into the ad> element of the page.

As mentioned, you don’t actually need to eval() here — but you do need to wait for the appendChild() command to execute on the browser window before jQuery is available for use.

Method 3: fetch()

Depending on your personal preference, there are two equivalent options for using fetch(). First is using fetch() with Promise chaining:

View the raw code as a GitHub gist

Second, you can use async & await to handle the Promise returned by fetch():

View the raw code as a GitHub gist

Either of these methods would be considered a way of loading an external JavaScript file directly from the console window.

Just remember that you don’t need eval() unless you’re loading a string containing a <script> tag, like in the document.write() example.

But wait — never use eval()!

As I mentioned in passing previously, eval() has security risks associated with it, as the MDN Docs explain well:

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.” — MDN Docs

Put simply, you should use Function() instead of eval() — but eval() is commonly used, so don’t be surprised if you see it around.

Using Function() would look like the following code example:

View the raw code as a GitHub gist

Syntax-wise, there is no difference — just swap Function() for eval().

But using Function() will improve the security and performance of your website or application, even when just loading an external library from the developer console.

Function()Creates a new Function object. Calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval. However, unlike eval, the Function constructor creates functions that execute in the global scope only.” — MDN Docs

I should add thee caveat that I find that eval() sometimes work for me when Function() doesn’t — for example, Function() seems to be blocked on some websites where eval() is not blocked, for whatever reason.

Typically, appendChild() will load the script just fine and will be the preferred method — with better performance and less security risk.

If you try the code examples yourself using jQuery, please keep in mind that there is a built-in dollar sign method $() that jQuery will overwrite.

Other options

You have many other options if you’re interested in loading multiple external files or tools using JavaScript.

For example, if you already have jQuery loaded on a page, you can use jQuery’s helper function $.getScript():

View the raw code as a GitHub gist

Some other potentially useful options for loading external scripts are:

Of these, jspm.io is especially interesting because it allows you to use a simple import() statement directly from the console window.

One thing to watch out for here is “namespace pollution” — the script you are importing may overwrite global variables already defined on that page. The previously-mentioned dollar sign method $() is an example of a namespace conflict with jQuery. You could also run into namespace issues if your version of jQuery conflicts with a version of jQuery already loaded on the website.

If namespace pollution is a concern, a tool like Tampermonkey may be helpful. Tampermonkey is a browser extension that can easily handle multiple running scripts on the same page without namespace collisions.

You might also consider RunKit, which is a website linked on every npm package (such as jQuery) that lets you try out any Node.js package in the browser, with no setup required. Here is the RunKit for jQuery. (I never have any luck using jQuery inside RunKit, but you may be able to make it work).

Similarly, CodeSandbox lets you easily sandbox any individual npm package or combination of npm packages without needing to install anything locally, as does CodePen via SkyPack.

Conclusion

It is common that a developer might want to test an external library or other JavaScript file using the browser’s development console.

For example, you might want to load jQuery, either for the purpose of manipulating the current page or just to practice syntax in the console.

Whether prototyping, learning, testing, or modifying an existing page, it can be very useful to load an external library from the developer console.

This article discussed three methods of loading an external JavaScript file from the console: document.write(), appendChild(), and fetch().

I provided an example using each method showing how to load jQuery from the browser’s console environment.

Alternatively, you might try other tools — like SystemJS, ModuleLoader, jspm.io, Tampermonkey, RunKit, or CodeSandbox — depending on your exact needs and personal preferences.

Hopefully, this article helps you unlock the full power of Chrome DevTools or Firefox’s Web Console.

Happy coding! 👏👍💯😄🧠️🏎

Further reading

  • GeeksforGeeks explains how to load external JavaScript in Angular:
Photo by Ehimetalor Akhere Unuabona on Unsplash

Dr. Derek Austin is the author of Career Programming: How You Can Become a Successful 6-Figure Programmer in 6 Months, now available on Amazon.

JavaScript
Programming
Software Engineering
Web Development
Software Development
Recommended from ReadMedium