本机JavaScript中的jQuery.getScript替代方案

时间:2013-05-30 15:06:20

标签: javascript jquery getscript

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

我查看了jQuery源代码,了解getScript是如何实现的,这样我就可以使用该方法使用本机JS加载脚本。但是,getScript只调用jQuery.get()

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

所以我的问题是,

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

谢谢!

8 个答案:

答案 0 :(得分:78)

这是一个带有回调功能的jQuery getScript替代方案:

function getScript(source, callback) {
    var script = document.createElement('script');
    var prior = document.getElementsByTagName('script')[0];
    script.async = 1;

    script.onload = script.onreadystatechange = function( _, isAbort ) {
        if(isAbort || !script.readyState || /loaded|complete/.test(script.readyState) ) {
            script.onload = script.onreadystatechange = null;
            script = undefined;

            if(!isAbort && callback) setTimeout(callback, 0);
        }
    };

    script.src = source;
    prior.parentNode.insertBefore(script, prior);
}

答案 1 :(得分:28)

您可以像这样获取脚本:

(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'));

答案 2 :(得分:10)

首先,感谢@ Mahn的回答。我在ES6中重写了他的解决方案并承诺,如果有人需要它,我将在这里粘贴我的代码:

const scriptUrl = 'https://www.google.com/recaptcha/api.js?onload=onRecaptchaLoad&render=explicit';
loadScript(scriptUrl).then(() => {
  console.log('script loaded');
}, () => {
  console.log('fail to load script');
});

用法:

EffectComposer

并且代码已经过了。

答案 3 :(得分:8)

使用此

var js_script = document.createElement('script');
js_script.type = "text/javascript";
js_script.src = "http://www.example.com/script.js";
js_script.async = true;
document.getElementsByTagName('head')[0].appendChild(js_script);

答案 4 :(得分:2)

这将完善以前的ES6解决方案,并且可以在所有现代浏览器中使用

加载并获取脚本作为承诺

const getScript = url => new Promise((resolve, reject) => {
  const script = document.createElement('script')
  script.src = url
  script.async = true

  script.onerror = reject

  script.onload = script.onreadystatechange = function() {
    const loadState = this.readyState

    if (loadState && loadState !== 'loaded' && loadState !== 'complete') return

    script.onload = script.onreadystatechange = null

    resolve()
  }

  document.head.appendChild(script)
})

用法

getScript('https://dummyjs.com/js')
.then(() => {
  console.log('Loaded', dummy.text())
})
.catch(() => {
  console.error('Could not load script')
})

也适用于JSONP端点

const callbackName = `_${Date.now()}`
getScript('http://example.com/jsonp?callback=' + callbackName)
.then(() => {
  const data = window[callbackName];

  console.log('Loaded', data)
})

另外,请注意所列的一些AJAX解决方案,因为它们受现代浏览器https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

的CORS政策约束

答案 5 :(得分:0)

Mozilla Developer Network provides an example,它可以异步工作,并且不使用HTMLScriptTag中未真正存在的“ onreadystatechange”(来自@ShaneX的回答):

function loadError(oError) {
  throw new URIError("The script " + oError.target.src + " didn't load correctly.");
}

function prefixScript(url, onloadFunction) {
  var newScript = document.createElement("script");
  newScript.onerror = loadError;
  if (onloadFunction) { newScript.onload = onloadFunction; }
  document.currentScript.parentNode.insertBefore(newScript, document.currentScript);
  newScript.src = url;
}

样品用量:

prefixScript("myScript1.js");
prefixScript("myScript2.js", function () { alert("The script \"myScript2.js\" has been correctly loaded."); });

但是,应考虑@Agamemnus的注释:调用onloadFunction时,脚本可能未完全加载。可以使用计时器setTimeout(func, 0)来使事件循环将添加的脚本最终确定为文档。事件循环最终会调用计时器后面的函数,并且脚本应该在此时准备就绪。

但是,也许应该考虑返回一个Promise而不是提供两个用于异常和成功处理的功能,这将是ES6方式。这也将不需要计时器,因为Promise由事件循环处理-因为在处理Promise时,脚本已由事件循环完成。

实施Mozilla的方法(包括Promises),最终代码如下:

function loadScript(url)
{
  return new Promise(function(resolve, reject)
  {
    let newScript = document.createElement("script");
    newScript.onerror = reject;
    newScript.onload = resolve;
    document.currentScript.parentNode.insertBefore(newScript, document.currentScript);
    newScript.src = url;
  });
}

loadScript("test.js").then(() => { FunctionFromExportedScript(); }).catch(() => { console.log("rejected!"); });

答案 6 :(得分:0)

这里有一些很好的解决方案,但是许多已经过时了。 @Mahn有一个good one,但正如注释中所述,它并不是$.getScript()的完全替代,因为回调不接收数据。我已经编写了自己的函数来代替$.get(),并在需要它来处理脚本时放到这里。我能够使用@Mahn的解决方案,并与当前的$.get()替代品一起对其进行一些修改,并提出一些效果很好且易于实现的东西。

function pullScript(url, callback){
    pull(url, function loadReturn(data, status, xhr){
        //If call returned with a good status
        if(status == 200){
            var script = document.createElement('script');
            //Instead of setting .src set .innerHTML
            script.innerHTML = data;
            document.querySelector('head').appendChild(script);
        }
        if(typeof callback != 'undefined'){
            //If callback was given skip an execution frame and run callback passing relevant arguments
            setTimeout(function runCallback(){callback(data, status, xhr)}, 0);
        }
    });
}

function pull(url, callback, method = 'GET', async = true) {
    //Make sure we have a good method to run
    method = method.toUpperCase();
    if(!(method === 'GET'   ||   method === 'POST'   ||  method === 'HEAD')){
        throw new Error('method must either be GET, POST, or HEAD');
    }
    //Setup our request
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
            //Once the request has completed fire the callback with relevant arguments
            //you should handle in your callback if it was successful or not
            callback(xhr.responseText, xhr.status, xhr);
        }
    };
    //Open and send request
    xhr.open(method, url, async);
    xhr.send();
}

现在,我们可以替换$.get()$.getScript(),它们的工作原理很简单:

pullScript(file1, function(data, status, xhr){
    console.log(data);
    console.log(status);
    console.log(xhr);
});

pullScript(file2);

pull(file3, function loadReturn(data, status){
    if(status == 200){
        document.querySelector('#content').innerHTML = data;
    }
}

答案 7 :(得分:0)

window.addEventListener('DOMContentLoaded',
       function() {
           var head = document.getElementsByTagName('HEAD')[0];
           var script = document.createElement('script');
           script.src = "/Content/index.js";
           head.appendChild(script);
       });