Javascript Require in browser console

99封情书 提交于 2019-12-02 08:51:49

A bit of an explanation is in order here.

When you add a script tag with a src dynamically the browser will fire off a request for the JavaScript file. But this operation, unlike a regular tag initially on the page, is asynchronous, it doesn't block. What this means is that the next line of code (in your case a call to myfunc) gets executed immediately, while the file is still being fetched. So if you want to defer code execution until after that script has been fetched, parsed, and executed, you need to register a callback. We can do this by listening for the script element's load event. There are two ways:

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

and assigning the function to the script elements onload property. The only real difference is that the addEventListener way allows you to attach multiple listeners, where as scr.onload can only have one value (like any other object property).

this works:

var scr = document.createElement('script');
scr.text = 'function sayHi() { alert("hi")}';
document.head.appendChild(scr);
sayHi()

...aaaaaand this works:

var scr = document.createElement('script');
scr.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js';
scr.onload = function() {
  $(function(){
    $('body').css({backgroundColor: 'red'});
  });
}
document.head.appendChild(scr);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!