本机JavaScript中的jQuery.getScript替代方案 [英] jQuery.getScript alternative in native JavaScript

查看:120
本文介绍了本机JavaScript中的jQuery.getScript替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态加载JS脚本,但是使用jQuery不是一个选项。

I'm trying to load JS scripts dynamically, but using jQuery is not an option.

我检查了jQuery源代码,看看 getScript ,以便我可以使用该方法使用本机JS加载脚本。但是,getScript只调用jQuery.get()

I checked jQuery source to see how getScript was implemented so that I could use that approach to load scripts using native JS. However, getScript only calls jQuery.get()

并且我无法找到get方法的实现位置。

and I haven't been able to find where the get method is implemented.

所以我的问题是,

使用本机JavaScript实现自己的getScript方法有什么可靠的方法?

What's a reliable way to implement my own getScript method using native JavaScript?

谢谢!

推荐答案

你可以像这样获取脚本: / p>

You can fetch scripts like this:

(function(document, tag) {
    var scriptTag = document.createElement(tag), // create a script tag
        firstScriptTag = document.getElementsByTagName(tag)[0]; // find the first script tag in the document
    scriptTag.src = 'your-script.js'; // set the source of the script to your script
    firstScriptTag.parentNode.insertBefore(scriptTag, firstScriptTag); // append the script to the DOM
}(document, 'script'));

这篇关于本机JavaScript中的jQuery.getScript替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆