Is there a simpler (native perhaps?) way to include an external script file in the Google Chrome browser?
Currently I’m doing it like this:
document.
In the modern browsers you can use the fetch to download resource (Mozilla docs) and then eval to execute it.
For example to download Angular1 you need to type:
fetch('https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js')
.then(response => response.text())
.then(text => eval(text))
.then(() => { /* now you can use your library */ })
If anyone, fails to load because hes script violates the script-src "Content Security Policy" or "because unsafe-eval' is not an allowed", I will advice using my pretty-small module-injector as a dev-tools snippet, then you'll be able to load like this:
imports('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js')
.then(()=>alert(`today is ${moment().format('ffffdd')}`));
<script src="https://raw.githack.com/shmuelf/PowerJS/master/src/power-moduleInjector.js"></script>
this solution works because:
Install tampermonkey and add the following UserScript with one (or more) @match
with specific page url (or a match of all pages: https://*
) e.g.:
// ==UserScript==
// @name inject-rx
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Inject rx library on the page
// @author Me
// @match https://www.some-website.com/*
// @require https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js
// @grant none
// ==/UserScript==
(function() {
'use strict';
window.injectedRx = rxjs;
//Or even: window.rxjs = rxjs;
})();
Whenever you need the library on the console, or on a snippet enable the specific UserScript and refresh.
This solution prevents namespace pollution. You can use custom namespaces to avoid accidental overwrite of existing global variables on the page.
Do you use some AJAX framework? Using jQuery it would be:
$.getScript('script.js');
If you're not using any framework then see the answer by Harmen.
(Maybe it is not worth to use jQuery just to do this one simple thing (or maybe it is) but if you already have it loaded then you might as well use it. I have seen websites that have jQuery loaded e.g. with Bootstrap but still use the DOM API directly in a way that is not always portable, instead of using the already loaded jQuery for that, and many people are not aware of the fact that even getElementById()
doesn't work consistently on all browsers - see this answer for details.)
It's been years since I wrote this answer and I think it's worth pointing out here that today you can use:
to dynamically load scripts. Those may be relevant to people reading this question.
See also: The Fluent 2014 talk by Guy Bedford: Practical Workflows for ES6 Modules.