google chrome devtools - Javascript Require in browser console -


when entering javascript in browsers console window:

1)

the following code works:

alert('hi'); 

2)

the following doesn't:

(function() { var scr = document.createelement('script'); scr.src = 'http://www.myrandomwebsite.com/myjs.js'; document.head.appendchild(scr); myfunc(); })() 

where myjs.js folder contains:

var myfunc = function(){alert('hi')}; 

explaining 2) snippet of code entered in case cause following code appear @ end of header tag in source code:

<script src="http://www.myrandomwebsite.com/myjs.js"></script> 

but function myfunc isn't being recognized, because following error message:

vm132:5 uncaught referenceerror: myfunc not defined

which leads me believe security measure, browsers don't run javascript code edited after page has loaded, or along lines.

question: there workaround of sorts here? whether function works require('...'); in programming languages. but can't be installing special extension, works on fly.

i move around lot, , work on different computers, , love able use of code have without needing carry usb me.

________________________ update ________________________

the solution @jared smith proposed worked perfectly. there 1 instance doesn't work (and understand why). when site has content-security-policy doesn't allow scripts loaded other urls or connections loaded:

for instance:

content-security-policy: script-src 'self' https://apis.google.com content-security-policy: connect-src 'self' https://apis.google.com 

and makes perfect sense. situation have own code run, wanted able have code stored on site, , use when travel or on other computers, without need of extracting them usb.

now understand sites whitelisting sources scripts loaded security reasons, don't understand why there isn't exception when done developers console. csp used prevent xss attacks , such, in console purposely using code , testing features.

question: there feature in console might allow scripts loaded alternative site? have been fiddling source script snippets haven't been able find option. or might there other unrelated work around?

a bit of explanation in order here.

when add script tag src dynamically browser fire off request javascript file. operation, unlike regular tag on page, asynchronous, doesn't block. means next line of code (in case call myfunc) gets executed immediately, while file still being fetched. if want defer code execution until after script has been fetched, parsed, , executed, need register callback. can listening script element's load event. there 2 ways:

scr.addeventlistener('load', function() { myfunc(); }); 

and assigning function script elements onload property. real difference addeventlistener way allows attach multiple listeners, scr.onload can have 1 value (like other object property).


Comments