判断JS文件是否加载完成再执行操作

Kevin 杂记 642 次浏览 17条评论

记一个JavaScript代码片段。有时需要判断用户是否加载完特定JS文件,然后再相应地触发事件。代码支持现代浏览器运行,不兼容IE7及以下。如果要兼容,可以透过readyState返回状态判断,具体见下文。

function checkJsLoading(url) {
	var carHead = document.getElementsByTagName('head')[0];
	var carJs = document.createElement('script');
	carJs.setAttribute('type', 'text/javascript');
	carJs.setAttribute('src', url);
	carHead.appendChild(carJs);
	carJs.onload = function() {
		...
	}
}
checkJsLoading('font-awesome.js');

添加IE旧版本兼容支持。

carJs.onreadystatechange = function() {
	if (carJs.readyState == 'loaded' || carJs.readyState == 'complete') {
		...
	}
}

评论列表

  1. #1

    Hi, very nice website, cheers!
    ——————————————————
    Need cheap and reliable hosting? Our shared plans start at $10 for an year and VPS plans for $6/Mo.
    ——————————————————
    Check here: https://www.reliable-webhosting.com/

  2. #2

    dapoxetine without a doctor dapoxetine generic https://dapoxetine.confrancisyalgomas.com/

  3. #3

    low dose naltrexone autoimmune in pediatric patients https://naltrexoneonline.confrancisyalgomas.com/

  4. #4

    what is generic dapoxetine called https://salemeds24.wixsite.com/dapoxetine

  5. #5

    using ivermectin to treat heartworms https://ivermectin.mlsmalta.com/

  6. #6

    dapoxetine tablets price https://dapoxetine.bee-rich.com/

  7. #7

    dapoxetine peptides https://ddapoxetine.com/

  8. #8

    where to buy cheap vidalista online https://vidalista40mg.mlsmalta.com/

  9. #9

    generic cialis 20 mg price https://wisig.org/

  10. #10

    amstyles.com https://amstyles.com/

  11. #11

    how does hydroxychloroquine work malaria https://hydroxychloroquinee.com/

  12. #12

    difference between viagra and tadalafil https://tadalafil.cleckleyfloors.com/

  13. #13

    when do you take viagra https://viaplz.com/

  14. #14

    low dose cialis bph https://cleckleyfloors.com/

  15. #15

    effectiveness of tamoxifen vs nolvadex https://tamoxifen.mrdgeography.com/

  16. #16

    took vidalista didn’t work https://vidalista.mlsmalta.com/

  17. #17

    sildenafil dose for bph http://cavalrymenforromney.com/

发表评论

电邮地址用于 Gravatar 头像显示,不会被公开可见。