jQuery getScript() vs document.createElement('script')

三世轮回 提交于 2019-12-03 05:56:58

jQuery appends the script element to head if present, or to document element otherwise. Under the hood the code is similar. The final result will be the same: both approaches execute new code in the global scope.

the documentation to Jquery method says:

Load a JavaScript file from the server using a GET HTTP request, then execute it.

That means the imported javascript will be straigt invoked after successful loading.

Appending to the head: It means the browser adds the script-tag as a last child and executes the content (it is the same if you add the tag manuelly at the end of the head tag). Appending to the body: It means the browser adds the script-tag as a last child of the body tag and executes that content (it is the same if you add the tag manuelly at the end of the body tag).

kronion

It is worth mentioning that jQuery's getScript function disables caching by default, meaning that browsers will download the script every time the page is requested (see previous answer here). Your loadScript function, on the other hand, should take advantage of caching.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!