Lazy loading JavaScript and Inline JavaScript

2019-02-02 14:39发布

I noticed in the <head> of my site (for work), there are a lot of <link rel="stylesheet" type="text/css" href="" /> and <script type="text/javascript" src=""> tags. There are even more JavaScript/CSS files that are only loaded for specific pages (we're using CodeIgniter, and the file paths are passed to the header view).

I was considering using a conditional/asynchronous loader (eg. yepnope.js, head.js, etc.), but I noticed a small problem with doing this.

In our views, there is inline JavaScript, some uses $(function(){}) some uses $(document).ready(function(){}), and some just has code (using jQuery) that's not in a ready block.

Without editing EVERY view file to wrap its code in a function and calling that when the JS files are loaded, is there a way to delay the inline code until the JavaScript is asynchronously loaded?

7条回答
Rolldiameter
2楼-- · 2019-02-02 15:25

Have a look at using headjs. It is a nice lightweight library that will do this all for you.

查看更多
登录 后发表回答